这将是一个简单的问题,但如果我的类路径中包含两个库,我找不到它们之间的区别以及使用哪一个?
That's going to be an easy one, but I cannot find the difference between them and which one to use, if I have both the lib's included in my classpath?
Hamcrest 匹配器方法返回 Matcher 并且 Mockito 匹配器返回 T.因此,例如:org.hamcrest.Matchers.any(Integer.class) 返回 org.hamcrest.Matcher 的实例,以及 org.mockito.Matchers.any(Integer.class)code> 返回 Integer 的一个实例.
Hamcrest matcher methods return Matcher<T> and Mockito matchers return T. So, for example: org.hamcrest.Matchers.any(Integer.class) returns an instance of org.hamcrest.Matcher<Integer>, and org.mockito.Matchers.any(Integer.class) returns an instance of Integer.
这意味着您只能在签名中需要 Matcher> 对象时使用 Hamcrest 匹配器 - 通常是在 assertThat 调用中.在调用模拟对象的方法的地方设置期望或验证时,您可以使用 Mockito 匹配器.
That means that you can only use Hamcrest matchers when a Matcher<?> object is expected in the signature - typically, in assertThat calls. When setting up expectations or verifications where you are calling methods of the mock object, you use the Mockito matchers.
例如(为了清楚起见,使用完全限定的名称):
For example (with fully qualified names for clarity):
@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 匹配器.因此,假设您想以某种精度(但不多)匹配双精度值.在这种情况下,您可以这样做:
If you want to use a Hamcrest matcher in a context that requires a Mockito matcher, you can use the org.mockito.Matchers.argThat matcher. It converts a Hamcrest matcher into a Mockito matcher. So, say you wanted to match a double value with some precision (but not much). In that case, you could do:
when(mockFoo.getBarByDouble(argThat(is(closeTo(1.0, 0.001))))).
thenReturn(mockBar);
这篇关于Mockito's Matcher vs Hamcrest Matcher?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
如何检测 32 位 int 上的整数溢出?How can I detect integer overflow on 32 bits int?(如何检测 32 位 int 上的整数溢出?)
return 语句之前的局部变量,这有关系吗?Local variables before return statements, does it matter?(return 语句之前的局部变量,这有关系吗?)
如何将整数转换为整数?How to convert Integer to int?(如何将整数转换为整数?)
如何在给定范围内创建一个随机打乱数字的 intHow do I create an int array with randomly shuffled numbers in a given range(如何在给定范围内创建一个随机打乱数字的 int 数组)
java的行为不一致==Inconsistent behavior on java#39;s ==(java的行为不一致==)
为什么 Java 能够将 0xff000000 存储为 int?Why is Java able to store 0xff000000 as an int?(为什么 Java 能够将 0xff000000 存储为 int?)