3

I'm using Hamcrest's containsInAnyOrder matcher when asserting REST response using Rest Assured. Here's an example of my assertion:

assertThat(
        body.jsonPath().getList("zones.name"),
        containsInAnyOrder(values.getName().toArray()));

First argument returns a List. Second argument (values.getName()) also returns a List. But Intellij IDEA shows an error on a mactcher: Unchecked generics array creation for varargs parameter. When I run this assertions, I get java.lang.AssertionError. When I convert second argument to an array, like values.getName().toArray(), I get everything working as expected.

So I can't understand why comparing a List with a List doesn't work, but List with an array does? Why do I need to convert the second argument to an array?

Vitali Plagov
  • 722
  • 1
  • 12
  • 31

2 Answers2

1

containsInAnyOrder accepts a T....

When you pass a List, you aren't comparing the elements in the body.jsonPath().getList("zones.name") to the elements in the values.getName(), but to a single-element array that contains the list itself. Since a string cannot be equal to a list, the assertion fails.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • Thank you for your answer. Sorry, I can't understand this statement: _a single-element array that contains the list itself_. Could you please explain it a bit? – Vitali Plagov Sep 05 '18 at 10:12
  • Suppose you have a list with `"a"` and `"b"`. When you pass that as an argument you won't get an array with `["a", "b"]`, but an array with `[list("a", "b")]` – Mureinik Sep 05 '18 at 10:35
  • But if I check an actual result which is a List in `body.jsonPath().getList("zones.name")`, why an expected result should be an array and not the same List? – Vitali Plagov Sep 05 '18 at 11:10
0

Because there is Collection of Matchers:

public static <T> Matcher<java.lang.Iterable<? extends T>> containsInAnyOrder(java.util.Collection<Matcher<? super T>> itemMatchers)

You could use something like containsInAnyOrder(equalTo("bar"), equalTo("foo")) but it is not so handy.

Saljack
  • 2,072
  • 21
  • 24