2011-12-01 40 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不兼容的更改”一节中讨论了此问题。 –

相关问题