有没有办法与Hamcrest对嵌套属性进行深度比较

Gau*_*wat 6 java unit-testing hamcrest

我在大多数测试中都使用了hamcrest,但遇到了一个问题,它无法在对象图中测试一个级别的属性.我的测试用例的剪辑如下

final List<Foo> foos= fooRepository.findAll(spec);
      assertThat(results, is(notNullValue()));
      assertThat(results, hasItem(hasProperty("id.fooID1", equalTo("FOOID1"))));
Run Code Online (Sandbox Code Playgroud)

所以在这里我想检查是否在foos列表中我有一个属性id.fooID1 equla到FOOID1.这是我向下一级检查我的嵌套属性.这目前在hamcrest中工作并且我得到以下错误.

java.lang.AssertionError: 
Expected: a collection containing hasProperty("id.fooID1", "FOOID1")
     but: No property "id.fooID1"
    at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
    at org.junit.Assert.assertThat(Assert.java:956)
    at org.junit.Assert.assertThat(Assert.java:923)
Run Code Online (Sandbox Code Playgroud)

有关此问题的任何帮助或解决方法.

eee*_*eee 19

你可以嵌套hasProperty来电:

assertThat(results, hasItem(hasProperty("id", hasProperty("fooID1", equalTo("FOOID1")))));
Run Code Online (Sandbox Code Playgroud)

对于更深的嵌套,这可能有点笨拙.


Cri*_*ini 6

通过这种简单的实用程序方法,我已经达到了您期望的结果:

private static <T> Matcher<T> hasGraph(String graphPath, Matcher<T> matcher) {

    List<String> properties = Arrays.asList(graphPath.split("\\."));
    ListIterator<String> iterator =
        properties.listIterator(properties.size());

    Matcher<T> ret = matcher;
    while (iterator.hasPrevious()) {
        ret = hasProperty(iterator.previous(), ret);
    }
    return ret;
}
Run Code Online (Sandbox Code Playgroud)

我可以在这样的断言中使用:

 assertThat(bean, hasGraph("beanProperty.subProperty.subSubProperty", notNullValue()));
Run Code Online (Sandbox Code Playgroud)

检查这是否有帮助