2009-07-06 15 views

Odpowiedz

107

Korzystanie JUnit 4.4 można wykorzystać assertThat() wraz z kodem Hamcrest (nie martw się, to wysyłają z JUnit, nie ma potrzeby dodatkowego .jar) w celu wytworzenia kompleksu własnym opisując twierdzi, w tym te, które działają na zbiorach:

import static org.junit.Assert.assertThat; 
import static org.junit.matchers.JUnitMatchers.*; 
import static org.hamcrest.CoreMatchers.*; 

List<String> l = Arrays.asList("foo", "bar"); 
assertThat(l, hasItems("foo", "bar")); 
assertThat(l, not(hasItem((String) null))); 
assertThat(l, not(hasItems("bar", "quux"))); 
// check if two objects are equal with assertThat() 

// the following three lines of code check the same thing. 
// the first one is the "traditional" approach, 
// the second one is the succinct version and the third one the verbose one 
assertEquals(l, Arrays.asList("foo", "bar"))); 
assertThat(l, is(Arrays.asList("foo", "bar"))); 
assertThat(l, is(equalTo(Arrays.asList("foo", "bar")))); 

Stosując to podejście będzie automagicznie uzyskać dobry opis dochodzić, gdy nie powiedzie się.

+1

Ooh, nie zdawałem sobie sprawy, że hamcrest wszedł do dystrybucji. Idź Nat! – skaffman

+0

Jeśli chcę potwierdzić, l składa się z elementów ("foo", "bar"), ale nie ma żadnych innych elementów - czy jest tam jakaś łatwa składnia? – ripper234

+0

Skorzystaj z powyższego fragmentu kodu i dodaj dodatkowy argument assertTrue (l.size() == 2) – aberrant80

4

Nie bezpośrednio, nie. Sugeruję użycie Hamcrest, który zapewnia bogaty zestaw pasujących reguł, które integruje się dobrze z JUnit (i innych ram testowania)

+0

nie skompilować z jakiegoś powodu (patrz http://stackoverflow.com/questions/1092981/hamcrests-hasitems): ArrayList actual = new ArrayList (); ArrayList expected = new ArrayList (); actual.add (1); expected.add (2); assertThat (rzeczywiste, hasItems (expected)); – ripper234

1

Rozwiązanie Joachima Sauera jest dobre, ale nie działa, jeśli masz już wiele oczekiwań, które chcesz zweryfikować. Może to pojawić się, gdy masz już wygenerowane lub stałe oczekiwanie w testach, do których chcesz porównać wynik, lub masz wiele oczekiwań, które mogą zostać połączone w wyniku. Więc zamiast korzystania dopasowujących można można po prostu użyć List::containsAll i assertTrue Dla przykładu:

@Test 
public void testMerge() { 
    final List<String> expected1 = ImmutableList.of("a", "b", "c"); 
    final List<String> expected2 = ImmutableList.of("x", "y", "z"); 
    final List<String> result = someMethodToTest(); 

    assertThat(result, hasItems(expected1)); // COMPILE ERROR; DOES NOT WORK 
    assertThat(result, hasItems(expected2)); // COMPILE ERROR; DOES NOT WORK 

    assertTrue(result.containsAll(expected1)); // works~ but has less fancy 
    assertTrue(result.containsAll(expected2)); // works~ but has less fancy 
}