亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 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 關注
  • 144 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號