为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 NUnit “Assert.That()”列表中的项目匹配某些条件?

如何使用 NUnit “Assert.That()”列表中的项目匹配某些条件?

C#
明月笑刀无情 2023-08-20 09:52:13
我正在编写一些单元测试并想检查结果列表。这是我正在做的一个简单的例子:[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..");}失败测试的输出:两个项目应该与此匹配..预期:正好 2 件但是是:没有项目输出并没有解释出了什么问题。说明:我有多个测试的测试数据。这就是为什么我想在每次测试中检查特定项目。我的问题:有没有办法检查列表中的项目计数并从中获取正确的消息NUnit?也许像Assert.That(result, Contains.Exacly(2).Items.Which(i => i.SomeProperty == "expectedValue"))
查看完整描述

2 回答

?
森林海

TA贡献2011条经验 获得超2个赞

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

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


查看完整回答
反对 回复 2023-08-20
?
白衣染霜花

TA贡献1796条经验 获得超10个赞

是的,一点没错!NUnit 约束可以链接在一起,以允许您在实际断言方面真正具有规范性。这样做的优点是,当测试失败时,您将获得更精确的错误消息 - 因此在我看来,在实际的 NUnit 断言中包含尽可能多的逻辑是一种很好的做法。

在这种情况下,我相信你可以写这样的东西:

Assert.That(result,
 Contains.Exactly(2).Items.Property(nameof(MyClass.ExpectedProperty)).EqualTo("expectedValue");



查看完整回答
反对 回复 2023-08-20
  • 2 回答
  • 0 关注
  • 82 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信