[英]Junit: assert that a list contains at least one property that matches some condition
我有一個方法將返回MyClass
類型的對象列表。 MyClass
具有許多屬性,但是我關心的是type
和count
。 我想編寫一個測試,斷言返回的列表至少包含一個符合特定條件的元素。 例如,我要在類型"Foo"
的列表中至少包含一個元素並計數1
。
我試圖弄清楚如何做到這一點,而又不逐字逐句地遍歷返回的列表並逐一檢查每個元素,如果我發現可以通過的元素,則會中斷,例如:
boolean passes = false;
for (MyClass obj:objects){
if (obj.getName() == "Foo" && obj.getCount() == 1){
passes = true;
}
}
assertTrue(passes);
我真的不喜歡這種結構。 我想知道是否有更好的方法來使用assertThat
和一些Matcher。
assertTrue(objects.stream().anyMatch(obj ->
obj.getName() == "Foo" && obj.getCount() == 1
));
或更可能的是:
assertTrue(objects.stream().anyMatch(obj ->
obj.getName().equals("Foo") && obj.getCount() == 1
));
我不知道為此使用Hamcrest是否值得,但很高興知道它在那里。
public class TestClass {
String name;
int count;
public TestClass(String name, int count) {
this.name = name;
this.count = count;
}
public String getName() {
return name;
}
public int getCount() {
return count;
}
}
@org.junit.Test
public void testApp() {
List<TestClass> moo = new ArrayList<>();
moo.add(new TestClass("test", 1));
moo.add(new TestClass("test2", 2));
MatcherAssert.assertThat(moo,
Matchers.hasItem(Matchers.both(Matchers.<TestClass>hasProperty("name", Matchers.is("test")))
.and(Matchers.<TestClass>hasProperty("count", Matchers.is(1)))));
}
與進口hamcrest
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
你可以用
assertThat(foos, hasItem(allOf(
hasProperty("name", is("foo")),
hasProperty("count", is(1))
)));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.