Mockito的Matcher与Hamcrest Matcher有何区别?

50

这很简单,但我找不到它们之间的区别以及如果我的类路径中同时包含这两个库时该使用哪一个?


1个回答

101

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(或Mockito 2中的org.mockito.hamcrest.MockitoHamcrest.argThat)。它将Hamcrest匹配器转换为Mockito匹配器。因此,假设您想要使用某些精度(但不是很多)匹配double值,则可以执行以下操作:
when(mockFoo.getBarByDouble(argThat(is(closeTo(1.0, 0.001))))).
    thenReturn(mockBar);

16
请注意,在Mockito 2中,与Hamcrest Matcher一起使用的argThat重载已经被移动到了MockitoHamcrestMockito 2有哪些新功能 在其“与1.10不兼容的更改”部分讨论了这个问题。 - Bryan Turner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接