我正在尝试使用 NUnit 对自定义 WPF 控件进行单元测试。该控件是按钮的 ListView,绑定(bind)到列表(DataContext 在控件的构造函数中设置)。
我想编写测试(例如)将项目添加到列表并检查是否将新按钮添加到 View 等。但是,当我在我的 NUnit 测试中将项目添加到列表时,它仍然报告 ListView 为空。不过,当我运行我的应用程序时一切正常。
我在下面包含了相关代码。我需要做什么来测试它?
XAML:
<ListView x:Class="SoundBlock"
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"
ItemsSource="{Binding Path=Sounds}">
<ListView.ItemTemplate>
<DataTemplate>
<Button Content="{Binding Title}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
类定义
public partial class SoundBlock : ListView
{
public SoundBlock(Board xiBoard)
{
// Initialize.
InitializeComponent();
// Set the data context for this block.
DataContext = xiBoard; // Board has an ObservableCollection<Sound>
// property called Sounds.
}
}
测试用例
[Test]
public void TestAddSound()
{
board = new Board();
block = new SoundBlock(board);
Assert.AreEqual(0, block.Items.Count);
sound = new Sound("sound.mp3");
board.Sounds.Add(sound);
Assert.AreEqual(1, block.Items.Count); // This fails - count is still 0
}
最佳答案
查看我的问题:Force binding in WPF
您必须强制绑定(bind),在显示控件之前它不会起作用。您可以将它放入一个新窗口并显示该窗口。
关于c# - 在 WPF 中对数据绑定(bind)进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8104850/