使用StaticResources测试WPF窗口

Jam*_*mes 11 wpf unit-testing

我有一个简单的Window,它引用了App.xaml中的StaticResource.

App.xaml资源定义:

<!-- Standard Text Box Style -->
<Style x:Key="textBoxStyleStd" TargetType="{x:Type TextBox}">
    <Setter Property="FontSize" Value="14" />
</Style>
Run Code Online (Sandbox Code Playgroud)

使用资源的窗口组件:

<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}}"/>
Run Code Online (Sandbox Code Playgroud)

在尝试对此窗口进行单元测试时,我收到错误:

System.Windows.Markup.XamlParseException:找不到名为"{textBlockStyleStd}"的资源.资源名称区分大小写.标记文件'Zpg; component/guicomponenets/screens/enteredindidscreen.xaml'中对象'stationIdTitle'出错'第23行位置71.

有没有办法解决?我的单元测试代码是:

[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();
}
Run Code Online (Sandbox Code Playgroud)

Jam*_*mes 13

谢谢肯特,

我看了你的建议,在大多数情况下,我同意模型应该被使用和测试,但是,有一些与控件相关的代码(例如TextBox可见性)我仍然想测试.为了解决这个问题,您可以创建应用程序的实例(但不要初始化它)并手动添加资源.这确实导致App.xaml和基本单元测试中的重复,但这允许我完成我想要的测试.

        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
        }       
Run Code Online (Sandbox Code Playgroud)

  • 有一个类似的问题,只需在创建实例旁边调用app.InitializeComponent().资源字典将填充.这就是Main方法的作用.这是main方法的片段,你可以跳过app.Run,​​因为我们在这里进行单元测试.[System.STAThreadAttribute()] [System.Diagnostics.DebuggerNonUserCodeAttribute()] public static void Main(){WPFComboBox.App app = new WPFComboBox.App(); app.InitializeComponent(); app.Run(); } (5认同)

Ken*_*art 7

在单元测试的上下文中,没有运行WPF应用程序.因此,Window不会找到资源.

我的方法是不对您的观点进行单元测试.相反,使用MVVM并对您的视图模型进行单元测试.如果要测试视图,请编写集成测试.您的集成测试实际上可以启动应用程序,因此更加贴近您的应用程序的实际运行.