c# - 如何将 "Assert.That()"列表中的项目与 NUnit 匹配某些条件?

标签 c# unit-testing nunit assert

我正在编写一些单元测试并想检查结果列表。

这是我正在做的一个简单例子:

[Test]
public void FilterSomething_Test()
{
    List<MyClass> testdata = new List<MyClass>
    {
        new MyClass { SomeProperty = "expectedValue" },
        new MyClass { SomeProperty = "expectedValue" },
        new MyClass { SomeProperty = "unexpectedValue" },
        new MyClass { SomeProperty = "unexpectedValue" },
        new MyClass { SomeProperty = null },
    }

    List<MyClass> result = FilterSomething(testdata);

    Assert.That(
        result.Where(r => r.SomeProperty == "expectedValue"),
        Has.Exactly(2).Items,
        "Two Items should match this..");
}

失败测试的输出:

Two Items should match this..

Expected: exactly 2 items

But was: no items

输出没有解释出了什么问题。

说明:我有多个测试的测试数据。这就是为什么我要检查每个测试中的特定项目。

我的问题:

有没有一种方法可以检查列表中的项目计数并从 NUnit 获取正确的消息

也许是这样的

Assert.That(result, Contains.Exacly(2).Items.Which(i => i.SomeProperty == "expectedValue"))

最佳答案

Matches 约束表达式专用于此。 这种情况下的用法可能如下所示:

Assert.That(result, 
    Has.Exactly(2).Matches<MyClass>(r => r.SomeProperty == "expectedValue"),
    "Two Items should match this..");

关于c# - 如何将 "Assert.That()"列表中的项目与 NUnit 匹配某些条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57413661/

相关文章:

javascript - C#:使用 Marionette 驱动程序选择下拉项

c# - 如果 "Presenter"在 "View"上设置属性是否违反了 MVP 模式?

c# - 使用对象初始值设定项语法时为 "In constructors and initializers, only property or field parameter bindings are supported"

c# - 如何查看网络连接是否更改状态?

unit-testing - 集成与单元测试

c# - 使用 NUnit 进行单元测试时获得所需/正确的装配路径

c# - 单元测试未涵盖 LINQ `Any`

c# - 值在索引 1 处不同 - 对于相等的嵌套数组

c# - oop 检查返回类型是父类还是子类

Python:模拟文件以进行单元测试