2013-02-13 5 views
74

DNS 검사를 수행하는 명령 줄 도구가 있습니다. DNS 검사가 성공하면 명령은 추가 작업을 진행합니다. Mockito를 사용하여 이것에 대한 단위 테스트를 작성하려고합니다. 나는 InetAddress 클래스의 정적 구현을 ​​조롱 InetAddressFactory을 사용하고Mockito : InvalidUseOfMatchersException

public class Command() { 
    // .... 
    void runCommand() { 
     // .. 
     dnsCheck(hostname, new InetAddressFactory()); 
     // .. 
     // do other stuff after dnsCheck 
    } 

    void dnsCheck(String hostname, InetAddressFactory factory) { 
     // calls to verify hostname 
    } 
} 

: 여기에 내 코드입니다. 여기에 공장에 대한 코드는 다음과 같습니다

public class InetAddressFactory { 
    public InetAddress getByName(String host) throws UnknownHostException { 
     return InetAddress.getByName(host); 
    } 
} 

여기 내 단위 테스트 케이스이다 :

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers! 
2 matchers expected, 1 recorded. 
This exception may occur if matchers are combined with raw values: 
    //incorrect: 
    someMethod(anyObject(), "raw String"); 
When using matchers, all arguments have to be provided by matchers. 
For example: 
    //correct: 
    someMethod(anyObject(), eq("String by matcher")); 

이 문제를 해결하는 방법에 대한 입력 : testPostDnsCheck() 테스트를 실행에

@RunWith(MockitoJUnitRunner.class) 
public class CmdTest { 

    // many functional tests for dnsCheck 

    // here's the piece of code that is failing 
    // in this test I want to test the rest of the code (i.e. after dnsCheck) 
    @Test 
    void testPostDnsCheck() { 
     final Cmd cmd = spy(new Cmd()); 

     // this line does not work, and it throws the exception below: 
     // tried using (InetAddressFactory) anyObject() 
     doNothing().when(cmd).dnsCheck(HOST, any(InetAddressFactory.class)); 
     cmd.runCommand(); 
    } 
} 

예외?

답변

156

오류 메시지는 솔루션을 매우 명확하게 설명합니다. 행

doNothing().when(cmd).dnsCheck(HOST, any(InetAddressFactory.class)) 

은 모든 원시 값 또는 모든 matchers를 사용해야하는 경우 하나의 원시 값과 하나의 matcher를 사용합니다. 원래 올바른 버전

doNothing().when(cmd).dnsCheck(eq(HOST), any(InetAddressFactory.class)) 
+6

내게 어리석은. 나는 왜 제 2 인자가 나에게 오류를주는 지 계속 분석했다. 명확히 해 주셔서 감사합니다. 나는 Mockito에게 아주 새로운데, 이것은 나의 첫 만남이다. – devang

+1

고마워요. 예외 메시지는 매우 혼란 스럽지만, 당신의 설명이 이해하기 매우 명확했습니다. –

17

내가 지금 오랫동안 같은 문제를 가지고 읽을 수있는, 나는 종종 매처 (Matchers)와 값을 혼합 필요하고 그 Mockito와 .... 최근까지 할 관리 결코! 나는이 게시물이 꽤 오래된 사람이라 할지라도 누군가에게 도움이되기를 바랍니다.

분명히 Mockito에서 Matcher와 AND 값을 함께 사용할 수 없지만 변수를 비교하기 위해 Matcher가 수락한다면? 즉 ... 문제를 해결하고 사실이 것 : eq이 예 'METAS'에서

when(recommendedAccessor.searchRecommendedHolidaysProduct(eq(metas), any(List.class), any(HotelsBoardBasisType.class), any(Config.class))) 
      .thenReturn(recommendedResults); 

그것은 미래의 어떤 하나의 도움이 될

+4

굉장합니다. 'org.mockito.Mockito.eq()' – javaPlease42

+1

올바른 임포트가 이제 org.mockito.ArgumentMatchers.eq()입니다. – sam

6

값의 기존 목록입니다 Mockito은 '아무튼 '최종'방법 조롱을 지원합니다 (지금 당장). 그것은 나에게 같은 InvalidUseOfMatchersException를 주었다.

나를위한 솔루션은 '최종'일 필요가없는 메소드의 일부를 별도의 액세스 가능하고 재정의 할 수있는 메소드에 넣는 것이 었습니다.

사용 사례에 따라 Mockito API을 검토하십시오.