Mockito的Matcher vs Hamcrest Matcher?
这将是一个简单的,但我找不到它们和使用哪一个,如果我有两个lib包含在我的类路径中?
Hamcrest匹配器方法返回Matcher
,Mockito匹配器返回T.因此,例如: org.hamcrest.Matchers.any(Integer.class)
返回org.hamcrest.Matcher
和org.mockito.Matchers.any(Integer.class)
返回Integer
一个实例。
这意味着只有在签名中需要Matcher>
对象时才能使用Hamcrest匹配器 – 通常在assertThat
调用中。 在设置调用模拟对象方法的期望或validation时,可以使用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);