Mockito的Matcher vs Hamcrest Matcher?

时间:2011-12-01 20:46:13

标签: java mockito hamcrest

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

1 个答案:

答案 0 :(得分:82)

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

这意味着只有在签名中需要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匹配器。所以,假设你想要一个精确匹配双值(但不是很多)。在这种情况下,您可以这样做:

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