ewo*_*wok 5 java junit unit-testing hamcrest
我有一个方法将返回类型的对象列表MyClass。 MyClass有很多属性,但我关心type和count。我想编写一个测试,断言返回的列表至少包含一个与特定条件匹配的元素。"Foo"例如,我想要 type和 count列表中至少有一个元素1。
我试图弄清楚如何做到这一点,而无需逐字循环返回的列表并单独检查每个元素,如果我找到一个通过的元素,则会中断,例如:
boolean passes = false;
for (MyClass obj:objects){
if (obj.getName() == "Foo" && obj.getCount() == 1){
passes = true;
}
}
assertTrue(passes);
Run Code Online (Sandbox Code Playgroud)
我真的不喜欢这个结构。我想知道是否有更好的方法来使用assertThat一些匹配器来做到这一点。
带 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;
Run Code Online (Sandbox Code Playgroud)
你可以测试
assertThat(foos, hasItem(allOf(
hasProperty("name", is("foo")),
hasProperty("count", is(1))
)));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16468 次 |
| 最近记录: |