[java] when I run mockito test occurs WrongTypeOfReturnValue Exception

Error detail:

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.

my code :

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

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

As you can see, I am calling when on updateItemAttributes (which does return a boolean) not on updateItemAttributesByJuId.

  1. Why is Mockito attempting to return a boolean from updateItemAttributesByJuId?
  2. How can this be rectified?

This question is related to java mockito

The answer is


TL;DR If some arguments in your test are null, be sure to mock the parameter call with isNull() instead of anyXXX().


I got this error when upgrading from Spring boot 1.5.x to 2.1.x. Spring boot ships with its own Mockito, which is now also upgraded to 2.x (see e.g. Dependencies of Spring boot 2.1.2)

Mockito has changed the behavior for the anyXXX() method, where XXX is String, Long, etc. Here is the javadoc of anyLong():

Since Mockito 2.1.0, only allow valued Long, thus null is not anymore a valid value As primitive wrappers are nullable, the suggested API to match null wrapper would be #isNull(). We felt this change would make tests harness much safer that it was with Mockito 1.x.

I'd suggest you debug to the point where your mock is about to be called and inspect, whether at least one argument is null. In that case make sure, that you prepare your mock with isNull() instead of e.g. anyLong().

So this:

when(MockedClass.method(anyString());

becomes:

when(MockedClass.method(isNull());

I'm using Scala and I've got this message where I've mistakenly shared a Mock between two Objects. So, be sure that your tests are independent of each other. The parallel test execution obviously creates some flaky situations since the objects in Scala are singleton compositions.


Error:

org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
String cannot be returned by size()
size() should return int
***
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. This exception might occur in wrongly written multi-threaded
tests.
Please refer to Mockito FAQ on limitations of concurrency testing.
2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to
stub spies -
- with doReturn|Throw() family of methods. More in javadocs for
Mockito.spy() method.

Actual Code:

@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

Solution to fix this issue:

1st Remove annotation “@Mock”.

private ByteString mockByteString;

2nd Add PowerMockito.mock

mockByteString = PowerMockito.mock(ByteString.class);

In my case the problem was caused by trying to mock a static method and forgetting to call mockStatic on the class. Also I forgot to include the class into the @PrepareForTest()


I recently had this issue. The problem was that the method I was trying to mock had no access modifier. Adding public solved the problem.


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.


I had this error because in my test I had two expectations, one on a mock and one on concrete type

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();

I fixed it by changing cls to be a mock as well


According to https://groups.google.com/forum/?fromgroups#!topic/mockito/9WUvkhZUy90, you should rephrase your

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

to

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

Missing @MockBean on the bean you want to mock


For me the issue were the multithreaded tests that were doing stubbing/verification on a shared mocks. It leaded to randomly throwing WrongTypeOfReturnValue exception.

This is not properly written test using Mockito. Mocks should not be accessed from multiple threads.

The solution was to make mocks local to each test.


For me this meant I was running this:

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

So what was happening is that mockito was detecting that a.method2() was being called, and telling me I couldn't return c from a.method2() which is wrong.

Fix: use the doReturn(c).when(b).method1(a) style syntax (instead of when(b.method1(a)).thenReturn(c);), which will help you discover the hidden bug more concisely and quickly.

Or in this particular case, after doing that it started showing the more accurate "NotAMockException", and I changed it to not longer try to set a return value from a non-mock object.


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.


Very interested problem. In my case this problem was caused when I tried to debug my tests on this similar line:

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

The important note is that the tests were running correctly without debugging.

In any way, when I replaced above code with below code snippet then I was able to debug the problem line without problems.

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

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"...


In my case the bean has been initialized using @Autowired annotation instead of @MockBean

So in this way mocking of DAOs and Services throws such exception


If you are using annotations, may be you need to use @Mock instead of @InjectMocks. Because @InjectMocks works as @Spy and @Mock together. And @Spy keeps track of recently executed methods and you may feel that incorrect data is returned/subbed.


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


Another reason for similar error message is trying to mock a final method. One shouldn't attempt to mock final methods (see Final method mocking).

I have also confronted the error in a multi-threaded test. Answer by gna worked in that case.