0

I have the follwoing test code:

Page<Long> users = userService.findAllUserIdsWithLocationsWithoutCategories(pageable);
assertEquals(1, users.getTotalElements());
assertThat(users.getContent(), hasSize(1));
assertThat(users.getContent(), containsInAnyOrder(user5.getId()));

but it fails with the following error:

java.lang.AssertionError: 
Expected: iterable with items [<132L>] in any order
     but: not matched: <132>

What am I doing wrong and how to fix it?

RamPrakash
  • 1,687
  • 3
  • 20
  • 25
alexanoid
  • 24,051
  • 54
  • 210
  • 410
  • 1
    Does `getContent()` by any chance return a `Collection`? – Turing85 Dec 22 '19 at 16:32
  • no, it returns `List` – alexanoid Dec 22 '19 at 16:36
  • From the looks of it, it seems that either `users.getContents()` or `user5.getId()` returns an `int` or `Integer`. – Turing85 Dec 22 '19 at 16:43
  • 1
    And `User.getId()` returns long also? It much seems that list has one Long <132L> and it does not match <132> , Integer ? – pirho Dec 22 '19 at 16:43
  • Hamcrest does not support auto-boxing (e.g. from `Integer` to `Long`), but you could [overload a Matcher to widen/narrowing the type](https://stackoverflow.com/questions/26437839/how-to-use-primitive-autoboxing-widening-with-hamcrest) – hc_dev Dec 22 '19 at 17:20

1 Answers1

1

Actual return types

You are calling getContent() on return value Page<Long>. This will return a List<Long> as the docs state:

List<T> getContent()

Returns the page content as List.

Suitable matcher

So you can use Hamcrest's Matchers for Collections. I would use hasItem() to check if the one item (e.g. user5.getId()) is contained in the list.

Matching the same types

But pay attention to the argument type you pass to hasItem(). The expected value should be of type Long or long (autoboxing), since your actual elements of List<Long> have type Long.

What is the return type of your argument user5.getId()?

The error-message shows you are expecting an int or Integer (because missing L for Long):

not matched: <132>

Whereas your List returns elements of Long (hence suffix L in the error-message):

iterable with items [<132L>]

Solution: cast or re-design

You can either cast the expected getId() to the required type Long: assertThat(users.getContent(), containsInAnyOrder( (Long) user5.getId() ));

Or you bravely re-design the method under test to return Page<Integer>. Rational behind: since most IDs are implemented as Integer (see user5.getId()) all related methods (like findAllUserIdsWithLocationsWithoutCategories) should respect that type in their signature and return Integers.

hc_dev
  • 8,389
  • 1
  • 26
  • 38