如何 "Assert.That()" 列表中的项目与 NUnit 匹配某些条件?
How to "Assert.That()" Items in a List match certain conditions with NUnit?
我正在编写一些单元测试并想检查结果列表。
这是我正在做的一个简单例子:
[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"))
是的,绝对! NUnit 约束可以链接在一起,以允许您在实际断言方面非常规范。这样做的好处是当你的测试失败时你会得到一个更准确的错误消息——所以在我看来,在实际的 NUnit 断言中包含尽可能多的逻辑是一个很好的做法。
在这种情况下,我相信你可以这样写:
Assert.That(result,
Contains.Exactly(2).Items.Property(nameof(MyClass.ExpectedProperty)).EqualTo("expectedValue");
有 Matches
专门用于此的约束表达式。
这种情况下的用法可能如下所示:
Assert.That(result,
Has.Exactly(2).Matches<MyClass>(r => r.SomeProperty == "expectedValue"),
"Two Items should match this..");
我正在编写一些单元测试并想检查结果列表。
这是我正在做的一个简单例子:
[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"))
是的,绝对! NUnit 约束可以链接在一起,以允许您在实际断言方面非常规范。这样做的好处是当你的测试失败时你会得到一个更准确的错误消息——所以在我看来,在实际的 NUnit 断言中包含尽可能多的逻辑是一个很好的做法。
在这种情况下,我相信你可以这样写:
Assert.That(result,
Contains.Exactly(2).Items.Property(nameof(MyClass.ExpectedProperty)).EqualTo("expectedValue");
有 Matches
专门用于此的约束表达式。
这种情况下的用法可能如下所示:
Assert.That(result,
Has.Exactly(2).Matches<MyClass>(r => r.SomeProperty == "expectedValue"),
"Two Items should match this..");