junit 用于复杂对象列表的Hamcrest匹配器,其中每个匹配器包含复杂对象列表

svdrlsy4  于 2022-11-11  发布在  其他
关注(0)|答案(3)|浏览(171)

抱歉标题太长,但我的问题如下;
我有这些课;

public class A {
    int a1;
    int a2;
    List<B> listOfB;
}

public class B {
    int b1;
    int b2;
    List<C> listOfC;
}

public class C {
    int c1;
    int c2;
}

如果B只Assert它所拥有的C列表,我将使用以下自定义匹配器; Matcher<Iterable<C>> cMatcher = Matchers.hasItems(allOf(hasProperty("c1", equalTo(c1)), hasProperty("c2", equalTo(c2))))
但是我如何从A执行Assert呢?我想在一个更大的作用域匹配器中使用这个C列表匹配器,它可以执行以下操作;
Matchers.hasItems(allOf(hasProperty("b1", equalTo(b1)), hasProperty("b2", equalTo(b2)), hasProperty("listOfC", cMatcher)))
因此,在某种程度上,我希望匹配listOfB中的B,其中已给定b1b2值,以及其listOfC,其中包含值为c1c2的特定C

1zmg4dgp

1zmg4dgp1#

很抱歉回答我自己的问题,但是我在最后给出的代码是正确的。内部列表C的匹配器约束有一些问题。
所以要在一个列表中匹配一个列表;
Matcher<Iterable<C>> cMatcher = Matchers.hasItems(allOf(hasProperty("c1", equalTo(c1)), hasProperty("c2", equalTo(c2))))
然后在更高的作用域匹配器中使用它;
Matchers.hasItems(allOf(hasProperty("b1", equalTo(b1)), hasProperty("b2", equalTo(b2)), hasProperty("listOfC", cMatcher)))
将符合我在我的问题中描述的情况。
我遇到的问题是我的C类中的一个字段,它的类型为Boolean,不知怎么的hasProperty("boolField", true)不匹配,说property "boolField" is not readable。可能是因为Boolean的getter方法没有得到get前缀in this question, it says primitive boolean works, while Boolean object fails in this situation

d5vmydt9

d5vmydt92#

虽然你 * 可以 * 创建一个复合Hamcrest匹配器,你所面临的困难概述了你的测试方法的缺点。
Law of Demeter建议您将测试绑定到每个类,而不是其他类。
A有一个正确的B列表是好的,但是那些C的行为完全取决于B,并且将属于 its 测试。

czfnxgou

czfnxgou3#

hasItems进行部分匹配。请使用containsInAnyOrder进行完全匹配。
http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html

相关问题