2011-12-01 19 views
26

Sarà facile, ma non riesco a trovare la differenza tra loro e quale usare, se ho entrambi i lib inclusi nel mio classpath?Mockito's Matcher vs Hamcrest Matcher?

+0

correlati: [? Come si Mockito matchers lavoro] (http://stackoverflow.com/a/22822514/1426891) –

risposta

71

Hamcrest metodi matcher restituiscono Matcher<T> e Mockito matchers T. ritorno Così, ad esempio: org.hamcrest.Matchers.any(Integer.class) restituisce un'istanza di org.hamcrest.Matcher<Integer>, e org.mockito.Matchers.any(Integer.class) restituisce un'istanza di Integer.

Ciò significa che è possibile utilizzare i rilevatori di Hamcrest solo quando è previsto un oggetto Matcher<?> nella firma, in genere nelle chiamate assertThat. Quando si impostano le aspettative o le verifiche in cui si chiamano i metodi dell'oggetto fittizio, si usano i corrispondenti Mockito.

Per esempio (con nomi completi per chiarezza):

@Test 
public void testGetDelegatedBarByIndex() { 
    Foo mockFoo = mock(Foo.class); 
    // inject our mock 
    objectUnderTest.setFoo(mockFoo); 
    Bar mockBar = mock(Bar.class); 
    when(mockFoo.getBarByIndex(org.mockito.Matchers.any(Integer.class))). 
     thenReturn(mockBar); 

    Bar actualBar = objectUnderTest.getDelegatedBarByIndex(1); 

    assertThat(actualBar, org.hamcrest.Matchers.any(Bar.class)); 
    verify(mockFoo).getBarByIndex(org.mockito.Matchers.any(Integer.class)); 
} 

Se si desidera utilizzare un matcher Hamcrest in un contesto che richiede un matcher Mockito, è possibile utilizzare il org.mockito.Matchers.argThat matcher. Converte un matcher di Hamcrest in un matcher Mockito. Quindi, supponiamo di voler abbinare un doppio valore con una certa precisione (ma non molto). In tal caso, si potrebbe fare:

when(mockFoo.getBarByDouble(argThat(is(closeTo(1.0, 0.001))))). 
    thenReturn(mockBar); 
+3

Basta notare che, in Mockito 2, il ' argThat' overload che funziona con Hamcrest 'Matcher's è stato spostato' MockitoHamcrest'. [Le novità di Mockito 2] (https://github.com/mockito/mockito/wiki/What%27s-new-in-Mockito-2#incompatible) ne discutono nella sezione "Incompatible changes with 1.10". –

Problemi correlati