c# - 在 WPF 中对数据绑定(bind)进行单元测试

标签 c# wpf data-binding nunit

我正在尝试使用 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/

相关文章:

c# - 我可以详细检查 OOP 的示例项目

c# - 在 Entity Framework 查询中使用 TransactionScope 是个好主意吗?

wpf - WPF中的2D CAD应用程序

wpf - WPF TreeView ,存储库,层次结构数据和WPF新手

data-binding - 绑定(bind)到动态生成的组件/元素的可绑定(bind)属性

c# - 通过反射访问 protected 字段时出现 FieldAccessException

c# - 主键生成方法

.net - 使 WPF 应用程序看起来像 Metro 风格,即使在 Windows 7 中也是如此? (窗口 Chrome/主题/主题)

c# - DataGridView 数据源

c# - 绑定(bind)到 BindingList<T> - 选择要绑定(bind)的内容?