[Fixed] Org.Mockito.Exceptions.Misusing.WrongTypeOfReturnValue

In this post, we will see how to fix Org.Mockito.Exceptions.Misusing.WrongTypeOfReturnValue.

There are two major reasons because of which you can get this Exception. These details are provided in Exception itself.

  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.

💡 Quick fix

If you are looking for quick solution, then you should change when() and thenReturn() combination to doReturn() and when() while calling a method on Spy.

To

Here factory is spy object.

Here is an example where we will reproduce the issue and fix it.

Mockito testcase:

Output

Once you change following line, you won’t get exception anymore.

To

Let’s understand why did we get this exception.

  • When you use spy, real code is executed by nature, so when we are calling factory.produce(), it is getting executed and returning a real Car object.
  • Constructor of Car has constructor agrument as engine(mock object) and it calls engine.getEngineParts(). This invocation is recorded by mockito as engine is a mock object.
  • Then when we want to return car, mockito throws the exception WrongTypeOfReturnValue complaining that the recorded invocation "engine.getEngineParts()" cannot return a Car.

So you should avoid using when() and thenReturn() in case of spy() as it calls actual method which may have side effects.

You should always use doReturn() or doThrow() with when() while dealing with spies.

Here is another example where we can have side effects of calling actual method while using when() and thenReturn()

Output

As you can see, here real method is called and test throws IndexOutOfBoundsException. We can avoid this issue by changing highlighted line to:

You might also get this exception while mocking final methods. You can not mock final methods using Mockito.

That’s all about how to fix Org.Mockito.Exceptions.Misusing.WrongTypeOfReturnValue Exception in Mockito.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *