2011-12-01 39 views
26

這將是一個容易的,但我無法找到它們之間的區別和使用哪一個,如果我的類路徑中都包含lib的話?Mockito's Matcher vs Hamcrest Matcher?

+0

相關:[?如何匹配器的Mockito工作(http://stackoverflow.com/a/22822514/1426891) –

回答

71

Hamcrest匹配方法返回Matcher<T>和匹配器的Mockito回報T.因此,舉例來說:org.hamcrest.Matchers.any(Integer.class)返回org.hamcrest.Matcher<Integer>一個實例,並org.mockito.Matchers.any(Integer.class)返回Integer一個實例。

這意味着您只能在簽名中預期使用Matcher<?>對象時使用Hamcrest匹配器 - 通常在assertThat調用中。當您在調用模擬對象的方法時設置期望或驗證時,請使用Mockito匹配器。

例如(與完全合格的名稱爲清楚起見):

@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)); 
} 

如果你想在一個需要匹配的Mockito上下文使用Hamcrest匹配器,你可以使用org.mockito.Matchers.argThat匹配。它將Hamcrest匹配器轉換爲Mockito匹配器。所以,假設你想以某種精度匹配一個double值(但不是很多)。在這種情況下,你可以這樣做:

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

剛提的是,在2的Mockito的' arg與Hamcrest'Matcher's一起工作的超載被移動了'MockitoHamcrest'。 [Mockito 2中的新增功能](https://github.com/mockito/mockito/wiki/What%27s-new-in-Mockito-2#incompatible)在其「與1.10不兼容的更改」一節中討論了此問題。 –

相關問題