IT TIP

mockito 테스트를 실행할 때 WrongTypeOfReturnValue Exception이 발생합니다.

itqueen 2020. 10. 22. 23:50
반응형

mockito 테스트를 실행할 때 WrongTypeOfReturnValue Exception이 발생합니다.


오류 세부 정보 :

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
Boolean cannot be returned by updateItemAttributesByJuId()
updateItemAttributesByJuId() should return ResultRich
This exception might occur in wrongly written multi-threaded tests.
Please refer to Mockito FAQ on limitations of concurrency testing.

내 코드 :

@InjectMocks
protected ItemArrangeManager arrangeManagerSpy = spy(new ItemArrangeManagerImpl());
@Mock
protected JuItemWriteService juItemWriteService;

when(arrangeManagerSpy
    .updateItemAttributes(mapCaptor.capture(), eq(juId), eq(itemTO.getSellerId())))
    .thenReturn(false);

보시다시피, 나는 whenon이 아닌 ( updateItemAttributesa를 반환하는 boolean) 호출 하고 updateItemAttributesByJuId있습니다.

  1. Mockito가 boolean에서 를 반환하려고하는 이유는 무엇 updateItemAttributesByJuId입니까?
  2. 이 문제를 어떻게 해결할 수 있습니까?

에 따르면 https://groups.google.com/forum/?fromgroups#!topic/mockito/9WUvkhZUy90 , 당신은 바꿔해야 당신의

when(bar.getFoo()).thenReturn(fooBar)

...에

doReturn(fooBar).when(bar).getFoo()

유사한 오류 메시지에 대한 또 다른 이유는 final메서드 를 모의하려는 것입니다. 최종 메소드를 모의해서는 안됩니다 ( Final method mocking 참조 ).

또한 다중 스레드 테스트에서 오류에 직면했습니다. 그 경우에 gna의 답변이 작동했습니다.


매우 흥미로운 문제입니다. 제 경우에는이 비슷한 줄에서 테스트를 디버깅하려고 할 때이 문제가 발생했습니다.

Boolean fooBar;
when(bar.getFoo()).thenReturn(fooBar);

중요한 점은 테스트가 디버깅없이 올바르게 실행되었다는 것입니다.

어떤 식 으로든 위 코드를 아래 코드 스 니펫으로 교체하면 문제없이 문제 줄을 디버깅 할 수있었습니다.

doReturn(fooBar).when(bar).getFoo();

최근에이 문제가 발생했습니다. 문제는 내가 모의하려는 방법에 액세스 수정자가 없다는 것입니다. 대중을 추가하면 문제가 해결되었습니다.


제 경우 문제는 정적 메서드를 모의하려고 시도 mockStatic하고 클래스 호출 잊었 기 때문에 발생했습니다 . 또한 클래스를 포함하는 것을 잊었습니다.@PrepareForTest()


나를 위해 이것은 내가 이것을 실행하고 있음을 의미합니다.

a = Mockito.mock(SomeClass.class);
b = new RealClass();
when(b.method1(a)).thenReturn(c); 
// within this method1, it calls param1.method2() -- note, b is not a spy or mock

무슨 무슨 일이 벌어지고 것은 그래서 mockito 그 감지 된 a.method2()호출되는 한, 나는 반환하지 수 말해 c에서 a.method2()하는 잘못된 것입니다.

수정 : 숨겨진 버그를보다 간결하고 빠르게 발견하는 데 도움이되는 doReturn(c).when(b).method1(a)스타일 구문 (대신 when(b.method1(a)).thenReturn(c);)을 사용합니다 .

또는이 특별한 경우에는 더 정확한 "NotAMockException"이 나타나기 시작했고 더 이상 모의 객체가 아닌 객체에서 반환 값을 설정하지 않도록 변경했습니다.


테스트에서 두 가지 기대치가 있었기 때문에이 오류가 발생했습니다.

MyClass cls = new MyClass();
MyClass cls2 = Mockito.mock(Myclass.class);
when(foo.bar(cls)).thenReturn(); // cls is not actually a mock
when(foo.baz(cls2)).thenReturn();

cls를 mock으로 변경하여 수정했습니다.


주석을 사용하는 경우 @InjectMocks 대신 @Mock을 사용해야 할 수 있습니다. @InjectMocks는 @Spy와 @Mock으로 함께 작동하기 때문입니다. 그리고 @Spy는 최근에 실행 된 메서드를 추적하므로 잘못된 데이터가 반환 / 구독되는 것을 느낄 수 있습니다.


오류:

org.mockito.exceptions.misusing.WrongTypeOfReturnValue :
size ()에 의해 문자열을 반환 할 수 없습니다.
size ()는 int를 반환해야합니다.
***
위의 오류를 읽는 이유가 확실하지 않은 경우.
위 구문의 특성으로 인해 다음과 같은 이유로 문제가 발생할 수 있습니다.
1.이 예외 잘못 작성된 다중 스레드
테스트 에서 발생할 있습니다 .
동시성 테스트의 제한 사항에 대해서는 Mockito FAQ를 참조하십시오.
2. 스파이는 when (spy.foo ()). then () 구문을 사용하여 스텁됩니다. doReturn | Throw () 계열의 메서드를 사용하여
스파이 스텁하는 것이 더 안전
합니다.
Mockito.spy () 메소드에 대한 javadocs에서 더 많이 .

실제 코드 :

@RunWith(PowerMockRunner.class)
@PrepareForTest({ Object.class, ByteString.class})

@Mock
private ByteString mockByteString;

String testData = “dsfgdshf”;
PowerMockito.when(mockByteString.toStringUtf8()).thenReturn(testData); 
// throws above given exception

이 문제를 해결하기위한 솔루션 :

1st "@Mock"주석을 제거합니다.

private ByteString mockByteString;

두 번째 추가 PowerMockito.mock

mockByteString = PowerMockito.mock(ByteString.class);

I recently encountered this issue while mocking a function in a Kotlin data class. For some unknown reason one of my test runs ended up in a frozen state. When I ran the tests again some of my tests that had previously passed started to fail with the WrongTypeOfReturnValue exception.

I ensured I was using org.mockito:mockito-inline to avoid the issues with final classes (mentioned by Arvidaa), but the problem remained. What solved it for me was to kill the process and restart Android Studio. This terminated my frozen test run and the following test runs passed without issues.


Missing @MockBean on the bean you want to mock


In my case, I was using both @RunWith(MockitoJUnitRunner.class) and MockitoAnnotations.initMocks(this). When I removed MockitoAnnotations.initMocks(this) it worked correctly.


I got this issue WrongTypeOfReturnValue because I mocked a method returning a java.util.Optional; with a com.google.common.base.Optional; due to my formatter automatically adding missing imports.

Mockito was just saying me that "method something() should return Optional"...


This is my case:

//given
ObjectA a = new ObjectA();
ObjectB b = mock(ObjectB.class);
when(b.call()).thenReturn(a);

Target target = spy(new Target());
doReturn(b).when(target).method1();

//when
String result = target.method2();

Then I get this error:

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
ObjectB$$EnhancerByMockitoWithCGLIB$$2eaf7d1d cannot be returned by method2()
method2() should return String

Can you guess?

The problem is that Target.method1() is a static method. Mockito completely warns me to another thing.

참고URL : https://stackoverflow.com/questions/11121772/when-i-run-mockito-test-occurs-wrongtypeofreturnvalue-exception

반응형