Search code examples
javatestingjunitmatchinghamcrest

How to assert a generic list of integers with Hamcrest?


I am trying to match a list of integers with Hamcrest, had look at a few examples online however I am getting runtime exceptions.

Can some please let me know what is the right syntax ?

List<Integer> numbers = Arrays.asList( 1, 2, 3, 4, 5 );
assertThat((List<Object>) numbers, hasItem(hasProperty("value", is(1))));
assertThat((List<Object>) numbers, hasItem(hasProperty("value", is(2))));
assertThat((List<Object>) numbers, hasItem(hasProperty("value", is(3))));
assertThat((List<Object>) numbers, hasItem(hasProperty("value", is(4))));
assertThat((List<Object>) numbers, hasItem(hasProperty("value", is(5))));

Thanks


Solution

  • If the order of the list items doesn't matter:

    assertThat(numbers, hasItems(1, 2, 3, 4, 5));
    

    If it does:

    assertThat(numbers, is(equalTo(Arrays.asList(1, 2, 3, 4, 5))));
    

    If the collection shouldn't include other elements then also check the size:

    assertThat(numbers, hasSize(5));