Mockito's Matcher vs Hamcrest Matcher? [英] Mockito's Matcher vs Hamcrest Matcher?

查看:19
本文介绍了Mockito's Matcher vs Hamcrest Matcher?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆