모키토:유효하지 않은 UseOfMatchers예외
나는 DNS 검사를 수행하는 명령줄 도구를 가지고 있다.DNS 확인이 성공하면 명령어는 추가 태스크를 진행한다.나는 모키토를 이용하여 이것을 위한 단위 시험을 작성하려고 한다.내 암호는 다음과 같다.
public class Command() {
// ....
void runCommand() {
// ..
dnsCheck(hostname, new InetAddressFactory());
// ..
// do other stuff after dnsCheck
}
void dnsCheck(String hostname, InetAddressFactory factory) {
// calls to verify hostname
}
}
InetAddressFactory를 사용하여 정적 구현을 조롱하는 경우InetAddress
여기 공장에 대한 코드가 있다.
public class InetAddressFactory {
public InetAddress getByName(String host) throws UnknownHostException {
return InetAddress.getByName(host);
}
}
여기 내 유닛 테스트 케이스가 있다.
@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();
}
}
실행 예외testPostDnsCheck()
테스트:
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"));
이 문제를 해결하는 방법에 대한 의견이 있으십니까?
오류 메시지는 해결책에 대한 개요를 보여준다.라인
doNothing().when(cmd).dnsCheck(HOST, any(InetAddressFactory.class))
모든 원시 값 또는 모든 행렬자를 사용해야 하는 경우 원시 값 하나와 매처 하나를 사용한다.올바른 버전은
doNothing().when(cmd).dnsCheck(eq(HOST), any(InetAddressFactory.class))
나는 오랫동안 같은 문제를 가지고 있었고, 종종 매처스와 가치관을 섞어야 했고, 모키토와 함께 그것을 해내지 못했다....최근까지! 나는 이 게시물이 꽤 오래된 것일지라도 누군가에게 도움이 되기를 바라며 여기에 해결책을 두었다.
Mockito에서 Matchers AND 값을 함께 사용하는 것은 분명 불가능하지만, Matcher가 변수를 비교하기 위해 수락하는 것이 있다면 어떨까?그렇게 하면 문제가 해결될 텐데...그리고 사실: eq가 있다.
when(recommendedAccessor.searchRecommendedHolidaysProduct(eq(metas), any(List.class), any(HotelsBoardBasisType.class), any(Config.class)))
.thenReturn(recommendedResults);
이 예에서 'metas'는 기존 값 목록이다.
그것은 미래에 도움이 될 것이다.모키토는 '최종' 방법(지금 당장)을 조롱하는 것을 지지하지 않는다.나도 마찬가지였어.InvalidUseOfMatchersException
.
나에게 해결책은 '최종'이 될 필요가 없는 방법의 부분을 별도의 접근성 및 재정의 가능한 방법에 넣는 것이었다.
사용 사례에 대해서는 Mockito API를 검토하십시오.
나의 경우 a씨를 조롱하려다 보니 예외조항이 제기됐다.package-access
방법의메서드 액세스 수준을 변경할 때package
로protected
예외는 없어졌다.예: Java 클래스 아래의 내부,
public class Foo {
String getName(String id) {
return mMap.get(id);
}
}
방법String getName(String id)
적어도 해야 한다 protected
조롱 메커니즘(하위 분류)이 작동할 수 있도록 레벨링한다.
모든 견습생들을 동원한 결과, 나도 같은 문제를 겪고 있었다.
"org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
1 matchers expected, 3 recorded:"
내가 조롱하려는 방법이 정적 방법(say Xyz.class)만을 포함하는 수업(say Xyz.class)의 정적 방법이라는 것을 알아내는 데 조금 시간이 걸렸고 나는 다음 줄 쓰는 것을 잊어버렸다.
PowerMockito.mockStatic(Xyz.class);
아마도 그것은 문제의 원인이 될 수 있기 때문에 다른 사람들을 도울 것이다.
누군가에게 도움이 될지도 몰라.Mocked 메소드는 다음과 같이 만들어져야 하며, mocked class가 되어야 한다.mock(MyService.class)
또 다른 옵션은 캡처를 사용하는 것이다: https://www.baeldung.com/mockito-argumentcaptor
// assume deliver takes two values
@Captor
ArgumentCaptor<String> address; // declare before function call.
Mockito.verify(platform).deliver(address.capture(), any());
String value = address.getValue();
assertEquals(address == "some@thing.com");
캡쳐자는 특히 캡처하려는 개체의 멤버 중 한 멤버가 임의 ID일 수 있고 다른 멤버는 당신이 검증할 수 있는 것이라고 말할 때 유용하다.
모키토를 사용하지 마십시오.임의의 XXXX()값을 동일한 유형의 메서드 매개 변수에 직접 전달하십시오.예:
A expected = new A(10);
String firstId = "10w";
String secondId = "20s";
String product = "Test";
String type = "type2";
Mockito.when(service.getTestData(firstId, secondId, product,type)).thenReturn(expected);
public class A{
int a ;
public A(int a) {
this.a = a;
}
}
참조URL: https://stackoverflow.com/questions/14845690/mockito-invaliduseofmatchersexception
'programing' 카테고리의 다른 글
모델 변경 사항을 감지하는 Vue 지시문 (0) | 2022.04.13 |
---|---|
Vuex 작업이 속성 값에 액세스할 수 없음 (0) | 2022.04.13 |
VueJs 로컬 자산 경로 (0) | 2022.04.13 |
VueJS에서 템플릿에 추가된 구성 요소를 동적으로 컴파일하는 방법 (0) | 2022.04.13 |
커밋하지 않고 상태가 Vuex에서 업데이트됨 (0) | 2022.04.13 |