我有一个ResourceDictionary包含在我的WPF项目的Application.Resources区域中。这如何使单元测试了解Application.Resources
从App.xaml中(在此SO response的方式):
的App.xaml:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary
Source="MyDictionary.xaml">
</ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
在这本词典,我有几个款式,包括页面风格:
MyDictionary.xaml:
<SolidColorBrush x:Key="PageBackgroundBrush"
Color="Black" />
<Style x:Key="PageStyle" TargetType="Page">
<Setter Property="Background" Value="{StaticResource ResourceKey=PageBackgroundBrush}" />
<Setter Property="Height" Value="Auto" />
<Setter Property="Width" Value="Auto" />
</Style>
MyPage.xaml:
<Page x:Class="MyProject.MyPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="250"
Title="Page"
Style="{StaticResource ResourceKey=PageStyle}"
>
<Grid>
</Grid>
</Page>
MyPage.xaml.cs
public class MyPage : Page
{
public MyPage()
{
// this part crashes during unit tests because 'PageStyle' was not found
InitializeComponent();
}
}
此安装方法的效果非常好,当两者Visual Studio中查看网页在设计模式和运行时项目。我正在使用Visual Studio's built in Unit Test tools。当我尝试为MyPage类(在构造函数触发时使用MyPage.xaml)进行单元测试时,我的测试失败。 MyPage.xaml使用Application.Resources中包含的字典中定义的样式。测试无法识别PageStyle,因为Application.Resources在单元测试开始时未包含,并且导致页面无法实例化。如何在我的单元测试中包含我的Application.Resources?或者,是否有更好的方式来运行WPF页面和窗口的单元测试?
为什么标记将成为单元测试的一部分? – 2012-02-02 23:03:21
我正在使用我当前的方法,主要是因为这是我知道测试我为这个类(从Page继承而来)构造函数的唯一方法。我接受其他选择。 – ford 2012-02-02 23:10:52
[这个问题](http://stackoverflow.com/questions/747166/testing-a-wpf-window-with-staticresources)实际上为这个问题提供了一个解决方案。 – Grochni 2014-09-05 06:23:50