Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Misuse of hamcrest hasItems

I have a list of Integers (current) and I want to check whether this list contains all elements from list expected and not even one element from list notExpected, so code looks like:

    List<Integer> expected= new ArrayList<Integer>();
    expected.add(1);
    expected.add(2);

    List<Integer> notExpected = new ArrayList<Integer>();
    notExpected.add(3);
    notExpected.add(4);

    List<Integer> current = new ArrayList<Integer>();
    current.add(1);
    current.add(2);


    assertThat(current, not(hasItems(notExpected.toArray(new Integer[expected.size()]))));

    assertThat(current, (hasItems(expected.toArray(new Integer[expected.size()]))));

So long so good. But when I add

    current.add(3);

the test is also green. Do I misused the hamcrest matcher? Btw.

    for (Integer i : notExpected)
        assertThat(current, not(hasItem(i)));

gives me the correct answer, but I thought that I just can easily use the hamcrest matcher for that. I'm using junit 4.11 and hamcrest 1.3

like image 864
matlockx Avatar asked Feb 18 '13 08:02

matlockx


1 Answers

hasItems(notExpected...) would only match current if all elements from notExpected were also in current. So with the line

assertThat(current, not(hasItems(notExpected...)));

you assert that current doesn't contain all elements from notExpected.

One solution to assert that current doesn't contain any elements from notExpected:

assertThat(current, everyItem(not(isIn(notExpected))));

and then you don't even have to convert the list to array. This variant maybe a bit more readable, but requires conversion to array:

assertThat(current, everyItem(not(isOneOf(notExpected...))));

Note that these matchers are not from CoreMatchers in hamcrest-core, so you will need to add a dependency on hamcrest-library.

<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-library</artifactId>
    <version>1.3</version>
</dependency>
like image 146
zagyi Avatar answered Sep 26 '22 04:09

zagyi