1

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?

Jordi
  • 20,868
  • 39
  • 149
  • 333
  • Just a wild guess, you could try something like: `assertThat(categorizedFuaDto.getMetainfos(), hasItems(hasProperty("key", equalTo(receivedMetaInfoValue.getKey()))), hasProperty("value", equalTo(receivedMetaInfoValue.getValue()))));` 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. – Damien O'Reilly Oct 15 '15 at 15:07
  • Thanks, it works. Nevertheless, the compiler warns me: `Type safety: A generic array of Matcher super Object> is created for a varargs parameter`. Any idea? – Jordi Oct 15 '15 at 15:24
  • Yes. So whatever class this returns: `categorizedFuaDto.getMetainfos()` Change the code in your test to: `assertThat(categorizedFuaDto.getMetainfos(), hasItems(Matchers. hasProperty("key", equalTo(receivedMetaInfoValue.getKey()))), hasProperty("value", equalTo(receivedMetaInfoValue.getValue()))));` See here for an example: https://stackoverflow.com/a/33123568/3899529 – Damien O'Reilly Oct 15 '15 at 15:31

2 Answers2

1

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.

Damien O'Reilly
  • 952
  • 5
  • 12
0

If you want to ensure that the same item (of your collection) fulfills both conditions at the same time, you'd better combine them in one single matcher with the AllOf matcher :

assertThat(categorizedFuaDto.getMetainfos(),
        hasItem(allOf(hasProperty("key", equalTo(receivedMetaInfoValue.getKey())), 
                        hasProperty("value", equalTo(receivedMetaInfoValue.getValue())))));
aymens
  • 714
  • 9
  • 7