【发布时间】:2012-02-25 15:08:02
【问题描述】:
我的 WPF 项目的 Application.Resources 区域中包含一个 ResourceDictionary。这个
来自 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 页面和窗口运行单元测试?
【问题讨论】:
-
为什么标记会成为单元测试的一部分?
-
我使用我当前的方法主要是因为这是我所知道的测试我为这个类(它继承自 Page)创建的构造函数的唯一方法。我愿意接受其他选择。
-
This question实际上为这个问题提供了解决方案。
标签: c# wpf visual-studio-2010 unit-testing xaml