Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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));
}

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...