我正在編寫一些單元測試并想檢查結果列表。這是我正在做的一個簡單的例子:[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..");

白衣染霜花
TA貢獻1796條經驗 獲得超10個贊
是的,一點沒錯!NUnit 約束可以鏈接在一起,以允許您在實際斷言方面真正具有規范性。這樣做的優點是,當測試失敗時,您將獲得更精確的錯誤消息 - 因此在我看來,在實際的 NUnit 斷言中包含盡可能多的邏輯是一種很好的做法。
在這種情況下,我相信你可以寫這樣的東西:
Assert.That(result, Contains.Exactly(2).Items.Property(nameof(MyClass.ExpectedProperty)).EqualTo("expectedValue");
- 2 回答
- 0 關注
- 144 瀏覽
添加回答
舉報
0/150
提交
取消