Search code examples
javahamcrest

Hamcrest collection assertions merge several hasProperty in one


Actually I'm testing an item of a collection contains a property key equalTo("key") and has a property value equalTo("value"), in two sentences:

assertThat(categorizedFuaDto.getMetainfos(), contains(hasProperty("key", equalTo(receivedMetaInfoValue.getKey()))));
assertThat(categorizedFuaDto.getMetainfos(), contains(hasProperty("value", equalTo(receivedMetaInfoValue.getValue()))));

Is it possible to merge them in one?


Solution

  • You could try something like:

    assertThat(
        categorizedFuaDto.getMetainfos(), hasItems(Matchers.<YourClass>
            hasProperty("key", equalTo(receivedMetaInfoValue.getKey())),
            hasProperty("value", equalTo(receivedMetaInfoValue.getValue()))
        )
    );
    

    Where is whatever class type this method returns returns: categorizedFuaDto.getMetainfos()

    See here for an example: https://stackoverflow.com/a/33123568/3899529

    But I'm not sure what benefit this gives you over what is in your question. It's nice to keep your tests as simple and readable as possible.