Mockito的Matcher与Hamcrest

Mockito的Matcher与Hamcrest

本文介绍了Mockito的Matcher与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<T>,而Mockito匹配器返回T.因此,例如:org.hamcrest.Matchers.any(Integer.class)返回org.hamcrest.Matcher<Integer>的实例,而org.mockito.Matchers.any(Integer.class)返回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<?>对象时(通常在assertThat调用中),才可以使用Hamcrest匹配器.在要调用模拟对象的方法的地方设置期望或验证时,请使用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匹配器.因此,假设您想以某种精度(但不是很多)匹配一个double值.在这种情况下,您可以执行以下操作:

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

07-29 21:14