Search code examples
junithamcrest

Hamcrest: dump current type and value


I am writing test with usage of Java library Hamcrest and it's non-fluent API makes it impossible to reason about expression types when complex expression evolves, like:

.andExpect(JsonUnitResultMatchers.json()
    .matches(CoreMatchers.anyOf(CoreMatchers.allOf(
         JsonMatchers.jsonPartEquals("id", "123"),
         JsonMatchers.jsonPartEquals("name", "test")))))

Is there always TRUE matcher that dumps type & value of currently active expression? Like:

.andExpect(JsonUnitResultMatchers.json()
    .matches(CoreMatchers.anyOf(CoreMatchers.allOf(

         Slf4jMatcher.logType(),
         Slf4jMatcher.logTypeAndToString(),

         ConsumerMatcher.apply(System.out::println),

         JsonMatchers.jsonPartEquals("id", "123"),
         JsonMatchers.jsonPartEquals("name", "test")))))

I don't like to step into Hamcrest code with debugger. It is unproductive to delve into someones internals.


Solution

  • I came up with ugly:

    .andExpect(JsonUnitResultMatchers.json()
      .matches(Matchers.hasItem(CoreMatchers.allOf(
         new BaseMatcher() {
             @Override
             public boolean matches(Object item) {
                 log.info("type: {}", item.getClass());
                 log.info("toString: {}", item.toString());
                 return true;
             }
             @Override
             public void describeTo(Description description) {}
         },
         JsonMatchers.jsonPartEquals("id", "123"),
         JsonMatchers.jsonPartEquals("name", "test")))))
    

    I hope there are some funny DSL...