这将是一个简单的,但我找不到它们之间的区别和使用哪一个,如果我在我的类路径中包含了这两个库?
发布于 2011-12-02 10:26:33
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匹配器。因此,假设您希望匹配一个具有一定精度(但不是很高)的双精度值。在这种情况下,您可以这样做:
when(mockFoo.getBarByDouble(argThat(is(closeTo(1.0, 0.001))))).
thenReturn(mockBar);https://stackoverflow.com/questions/8348046
复制相似问题