背景
测试过程中,需要校验查询列表 返回数据的正确性。
常见的需求如:
- 验证查询条件正确性:输入某查询条件,验证返回结果的List所有记录的 该字段 均为输入条件;
- 验证数据正确性:验证查询结果中,某字段不能为空,某字段一定需要 > 0,某字段是个List,但是List的Size一定不为0;
- 添加数据后,查询列表可以包含该数据;
foreach 理论上也可以,但是每次写起来有点麻烦,就可以使用 hamcrest
本文地址:https://www.cnblogs.com/hchengmx/p/17612768.html
方式
@Test
void object_list_test(){
List<Person> list = Arrays.asList(
new Person("bob", "andy"),
new Person("bob", "judy")
);
//Test not empty list
assertThat(list, not(IsEmptyCollection.empty()));
//Test every object property
assertThat(list, everyItem(hasProperty("firstName",not(blankOrNullString()))));
assertThat(list, everyItem(hasProperty("firstName",is("bob"))));
//Test contains object property
assertThat(list, hasItem(hasProperty("lastName",is("andy"))));
//Test contains object
Person person = new Person("bob","andy");
assertThat(list, hasItem(person));
assertThat(list, IsCollectionWithSize.hasSize(2));
}
参考资料:
JUnit - How to test a List - Mkyong.com
org.hamcrest.collection (Hamcrest)