2011-12-01 4 views
26

그게 쉬운 일이 될거야,하지만 난 둘 다 libpath 내 수업 경로에 포함되어 있다면, 그들과 어떤 하나를 사용하는 차이점을 찾을 수 없습니까?Mockito의 Matcher 대 Hamcrest의 Matcher?

+0

관련을 [? Mockito 일을 정합 할 방법] (http://stackoverflow.com/a/22822514/1426891) –

답변

71

Hamcrest 정규 방법은 Matcher<T> 돌아가 Mockito 예를 들어, 그래서 반환 T. 정합 기 : org.hamcrest.Matcher<Integer>의 인스턴스를 반환 org.hamcrest.Matchers.any(Integer.class)org.mockito.Matchers.any(Integer.class)Integer의 인스턴스를 반환합니다.

즉, Matcher<?> 개체가 서명에서 예상되는 경우 (일반적으로 assertThat 호출시)에만 Hamcrest 매처를 사용할 수 있습니다. mock 객체의 메소드를 호출 할 때 expectations이나 verification을 설정할 때, Mockito matchers를 사용합니다. 예를 들어 (선명도에 대한 정규화 된 이름)

: 당신이 Mockito의 정규 표현을 필요로하는 컨텍스트에서 Hamcrest의 정규 표현을 사용하려면

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

, 당신은 org.mockito.Matchers.argThat 정규 사용할 수 있습니다. 그것은 Hamcrest matcher를 Mockito matcher로 변환합니다. 따라서 double 값을 약간의 정밀도로 일치 시키려고한다고 가정합니다 (그다지 많지는 않음). 이 경우, 당신은 할 수 :

when(mockFoo.getBarByDouble(argThat(is(closeTo(1.0, 0.001))))). 
    thenReturn(mockBar); 
+3

그냥 지적을, 그 Mockito 2에있는' 그것은 Hamcrest와 함께 작동하는 과부하입니다. Matcher's는'MockitoHamcrest'로 옮겨졌습니다. [Mockito 2의 새로운 기능] (https://github.com/mockito/mockito/wiki/What%27s-new-in-Mockito-2#incompatible)에서는 "1.10의 호환되지 않는 변경 사항"섹션에서 이에 대해 설명합니다. –

관련 문제