2013-02-18 10 views
8

mam listę liczb całkowitych (bieżący) i chcę, aby sprawdzić, czy ta lista zawiera wszystkie elementy z listy oczekiwanych i nawet jeden element z listy notExpected, więc kod wygląda następująco:Nadużywanie hamcrest hasItems

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

Tak długo tak dobrze. Ale gdy dodaję test jest także zielony. Czy źle wykorzystałem hamcrest matcher? Btw.

daje mi poprawną odpowiedź, ale pomyślałem, że po prostu mogę łatwo użyć do tego celu hamcrest. Używam JUnit 4.11 i hamcrest 1.3

Odpowiedz

9

hasItems(notExpected...) będzie tylko dopasować current jeśli wszystkie elementy z notExpected były również w current. Więc z linii

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

Ci twierdzą, że current nie zawiera wszystkie elementy z notExpected.

Jednym z rozwiązań twierdzą, że current nie zawiera żadnych elementów z notExpected:

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

a potem nawet nie trzeba konwertować listy do tablicy. Ten wariant może nieco bardziej czytelne, ale wymaga konwersji do tablicy:

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

Zauważ, że te dopasowujące nie są z CoreMatchers w hamcrest-core, więc trzeba będzie dodać zależność od hamcrest-library.

<dependency> 
    <groupId>org.hamcrest</groupId> 
    <artifactId>hamcrest-library</artifactId> 
    <version>1.3</version> 
</dependency> 
Powiązane problemy