I have a simple Window with a reference to a StaticResource in the App.xaml.
App.xaml resource definition:
<!-- Standard Text Box Style -->
<Style x:Key="textBoxStyleStd" TargetType="{x:Type TextBox}">
<Setter Property="FontSize" Value="14" />
</Style>
Window componets using the resource:
<TextBlock Grid.Column="1" Grid.Row="0" Name="stationIdTitle"
Style="{StaticResource textBlockStyleStd}"
VerticalAlignment="Center" HorizontalAlignment="Center"
Text="{LocText Key=Title, Dict={StaticResource Dictionary},
Assembly={StaticResource Assembly}}"/>
When trying to unit test this Window I get the error:
System.Windows.Markup.XamlParseException: Cannot find resource named '{textBlockStyleStd}'. Resource names are case sensitive. Error at object 'stationIdTitle' in markup file 'Zpg;component/guicomponenets/screens/enterstationidscreen.xaml' Line 23 Position 71.
Is there any way around this? My unit test code is:
[Test]
public void TestEnterKeyPressedNoText()
{
IPickingBusinessObject pickingBusinessObject = mock.StrictMock<IPickingBusinessObject>();
EnterStationIdScreen objectUnderTest = new EnterStationIdScreen(pickingBusinessObject);
Assert.AreEqual(Visibility.Visible, objectUnderTest.stationIdError.Visibility);
Assert.AreEqual("werwe", "oksdf");
Replay();
objectUnderTest.EnterKeyPressed();
Verify();
}
Thanks Kent,
I looked at your suggestions and in most scenarios I agree models should be used and tested however, there is some code associated with the controls (e.g. TextBox visibility) I still wanted to test. To get round this you can create an instance of your Application (but not initialize it) and add the resources manually. This does lead to duplication in the App.xaml and the base unit test but this allows me to complete the tests I wanted.
if (Application.Current == null)
{
App application = new App();
#region Add Static Resources from the App.xaml
Style textBoxStyle = new Style(typeof(TextBox));
textBoxStyle.Setters.Add(new Setter(TextBox.FontSizeProperty, 14d));
Style textBlockStyle = new Style(typeof(TextBlock));
textBlockStyle.Setters.Add(new Setter(TextBlock.FontSizeProperty, 14d));
application.Resources.Add("TextBoxStyleStd", textBoxStyle);
application.Resources.Add("TextBlockStyleStd", textBlockStyle);
application.Resources.Add("TextBlockStyleError", textBlockStyle);
application.Resources.Add("Assembly", "Zpg");
#endregion
}
In the context of your unit test, there is no WPF application running. Therefore, the Window
won't find the resource.
My way around this would be to not unit test your views. Instead, use MVVM and unit test your view models. If you want to test your views, write integration tests instead. Your integration tests can actually kick off the application and therefore much more closely imitate the real running of your app.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With