2013-02-18 19 views
8

Ho una lista di interi (corrente) e voglio verificare se questa lista contiene tutti gli elementi dalla lista prevista e neppure un elemento dall'elenco notExpected, quindi codice simile:Abuso di hasItems hamcrest

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

Così tanto bene. Ma quando aggiungo

current.add(3); 

il test è anche verde. Ho abusato del Matcher di Hamcrest? Btw.

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

mi dà la risposta corretta, ma ho pensato che ho appena posso usare facilmente il matcher hamcrest per questo. Sto usando JUnit 4.11 e hamcrest 1,3

risposta

9

hasItems(notExpected...) sarebbe partita solo current se tutti gli elementi da notExpected erano anche in current. Quindi, con la linea

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

si affermi che current non contiene tutti gli elementi da notExpected.

Una soluzione per affermare che current non contiene alcun elemento da notExpected:

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

e quindi non hanno nemmeno bisogno di convertire l'elenco di array. Questa variante forse un po 'più leggibile, ma richiede la conversione a matrice:

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

Si noti che queste matchers non sono da CoreMatchers in hamcrest-core, quindi sarà necessario aggiungere una dipendenza hamcrest-library.

<dependency> 
    <groupId>org.hamcrest</groupId> 
    <artifactId>hamcrest-library</artifactId> 
    <version>1.3</version> 
</dependency> 
Problemi correlati