Search code examples
javajunithamcrest

JUnit hamcrest Long comparison


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?


Solution

  • 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.