假设我有一个List<A>
class A {
private Integer val;
private String name;
}
在我的测试用例中,我得到了这个列表,它的大小和内容都不确定,我想做的是将我知道必须在列表中的两个列表元素的val
字段与给定的name
字段进行比较;
List<A> list = logic.getList();
assertThat(list, allOf(hasItems(hasProperty("name", equalTo("first")),
hasItems(hasProperty("val", equalTo(***value from another member with name = "second"))));
我如何才能做到这一点,或者这是甚至可能与Hamcrest匹配?
3条答案
按热度按时间jvidinwx1#
您可以根据自己的需要实现自定义
Matcher
,例如,检查某些具有名称的项是否具有相同值字段:laawzig22#
编写自定义匹配器可以清理测试逻辑:
然后,使用它:
或者,如果您不想创建A的示例来创建匹配器,请创建一个AMatcher构造函数,该构造函数接受您的“name”和“瓦尔”参数。
hyrbngr73#
不得不这么做。
用途:
(Java集合)
确保,类A重写对象等于方法,比较瓦尔和name。