2011-12-14 2 views
2

기본 값에 대한 맞춤 matcher를 작성하는 방법을 찾으려고합니다. 다음 맞춤 테스트가 있다고 가정 해 보겠습니다.Mockito - 기본 Matcher를 일치 시키려고 할 때 Custom Matcher가 NPE를 던졌습니다.

class IsEven extends ArgumentMatcher<Integer> { 
    public boolean matches(Object i) { 
     return ((Integer) i) % 2 == 0; 
    } 
} 

다음 테스트를 실행합니다. '조롱'메서드가 클래스의 이미 조롱 인스턴스 인 '것으로 someMethod'

@Test 
public void primatives() { 

    mocked.someMethod(2); 

    ArgumentMatcher<Integer> customMatcher = new IsEven(); 

    // ! Throws NPE ! 
    Mockito.verify(mocked).someMethod(Mockito.argThat(customMatcher)); 

} 

NullPointerException을하는 이유는 Mockio.argThat 방법은 항상 내가 할 수없는 추측하고있어 널 (null)을 반환한다는 것입니다 정수로 다시 autoboxed 될 수 있습니다.

나는이 공통점이 일반적인 사용 사례 인 것처럼 느낍니다.

감사합니다, 로이

답변

6

.. 읽기 자바 독 도움 : 드문 경우

매개 변수가 원시적 다음 해야 사용 관련 intThat이 (있다), floatThat() 등의 방법. 이렇게하면 autounboxing 중에 NullPointerException을 피할 수 있습니다.

0

모든 메소드에 대해 when()을 사용하여 해당 호출 대신 doThrow(), doAnswer(), doNothing(), doReturn() 및 doCallRealMethod()를 사용할 수 있습니다.

스텁 객체에 대한 스텁 메소드 스텁 객체 (아래 참조)에서 스텁 메소드를 두 번 이상 반복하여 테스트 도중에 모의 객체의 동작을 변경해야합니다. 하지만 모든 스텁 전화에 대해 대체 전화 대신 when()을 사용하는 것이 좋습니다.

when(mock.foo()).thenThrow(new RuntimeException()); 

    //Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown. 
    when(mock.foo()).thenReturn("bar"); 

    //You have to use doReturn() for stubbing: 
    doReturn("bar").when(mock).foo(); 
관련 문제