Mockito的Matcher vs Hamcrest Matcher?

tin*_*tin 36 java hamcrest mockito

这将是一个简单的,但我找不到它们和使用哪一个,如果我有两个lib包含在我的类路径中?

jhe*_*cks 90

Hamcrest匹配器方法返回Matcher<T>,Mockito匹配器返回T.因此,例如:org.hamcrest.Matchers.any(Integer.class)返回一个实例org.hamcrest.Matcher<Integer>,并org.mockito.Matchers.any(Integer.class)返回一个实例Integer.

这意味着只有Matcher<?>在签名中assertThat需要一个对象时才能使用Hamcrest匹配器- 通常是在调用中.在设置调用模拟对象方法的期望或验证时,可以使用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));
}
Run Code Online (Sandbox Code Playgroud)

如果要在需要Mockito匹配器的上下文中使用Hamcrest匹配器,可以使用org.mockito.Matchers.argThat匹配器.它将Hamcrest匹配器转换为Mockito匹配器.所以,假设你想要一个精确匹配双值(但不是很多).在这种情况下,您可以这样做:

when(mockFoo.getBarByDouble(argThat(is(closeTo(1.0, 0.001))))).
    thenReturn(mockBar);
Run Code Online (Sandbox Code Playgroud)

  • 只是注意到,在Mockito 2中,与Hamcrest`Matcher`s合作的`argThat`重载被移动了`MockitoHamcrest`.[Mockito 2中的新功能](https://github.com/mockito/mockito/wiki/What%27s-new-in-Mockito-2#incompatible)在"与1.10不兼容的更改"部分讨论了这一点. (8认同)