How To: Validate background color or other custom properties of WPF control in Coded UI Test

Coded UI Test uses accessibility (UI Automation) for testing of WPF application.  This accessibility (UI Automation) infrastructure only exposes a subset of control properties which is limiting in some cases.  For example, there is no easy way for the user to validate a background color of a panel that changes based on certain condition (assuming that is important to the user).

One workaround that is possible in this case is to use ItemStatus property of UI Automation. For example, in the below XAML snippet, just by adding the line in bold, the color of the ThirdButton is exposed as ItemStatus & can be validate using Coded UI Test now.

 <Button Name="FirstButton" Background="Green">First Button</Button>
<Button Name="SecondButton" Background="Blue">Second Button</Button>
<Button Name="ThirdButton" Background="Red"
        AutomationProperties.ItemStatus="{BindingRelativeSource={RelativeSource Self}, Path
 =Background}" >
    Third Button
</Button> 

Alternatively, if you want ItemStatus to get set on all the buttons, you can also use WPF Styles.  For example,

 <Window.Resources>
    <Style TargetType="Button">
        <Setter Property="AutomationProperties.ItemStatus"
                Value="{Binding RelativeSource={RelativeSource Self}, Path=Background}" />
    </Style>
</Window.Resources>

The above can ensure that the ItemStatus is set for all the buttons.

To get the ItemStatus, you can use the utility library that I had published a while back.

This approach has two issues -

  1. It requires you to update your product code.
  2. This can expose only one custom property at a time.

Note - The same problem is not there for Web or Win32 controls because there we have alternative means – MSHTML and windows messages respectively.