Question

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

Was it helpful?

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));

OTHER TIPS

To verify that the collection contains a specific item:

assertThat(numbers, hasItem(3));

To verify that the collection contains several items:

assertThat(numbers, hasItems(3, 4));

To verify that the collection contains exactly specific items:

assertThat(numbers, contains(1, 2, 3, 4, 5))

To verify that the collection contains specific items, not worrying about order:

assertThat(numbers, containsInAnyOrder(5, 4, 3, 1, 2))

Just use

assertThat(numbers, hasItem(1));
...

Or

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

Order doesn't matter here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top