[Solved] org.mockito.exceptions.misusing.WrongTypeOfReturnValue

WrongTypeOfReturnValue is RuntimeException and Subclass of MockitoException.  It throws when :

  1.  It might occurred because of wrongly written multi-threaded tests.
  2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies with doReturn|Throw() family of methods. 


  • WrongTypeOfReturnValue(String message) : Will throw exception with message.


Below case to show you on what case Mockito will throw WrongTypeOfReturnValue .

import static org.mockito.Mockito.*;
import static org.junit.Assert.*;

import org.junit.Test;

public class NestedWhen {
public class Bar {

public class Foo {
Bar getBar() {
return new Bar();

public class Product {
Bar bar;

Product(Foo f) {
bar = f.getBar();

public class ProductService {
Foo foo;

ProductService(Foo f) {
foo = f;

Product produce() {
return new Product(foo);

public void nestedWhenTest() {
Foo mfoo = mock(Foo.class);
Product mpoo = mock(Product.class);
ProductService productService = spy(new ProductService(mfoo));
// throw WrongTypeOfReturnValue exception here!!!


NestedWhen$Product$$EnhancerByMockitoWithCGLIB$$4418933b cannot be returned by getBar()
getBar() should return Bar
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.

at com.facingissuesonit.mockito.MockitoTestExamples.NestedWhen.nestedWhenTest(NestedWhen.java:44)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)


Here above code is throwing this exception because spy execute the real code by nature, so when calling “productService.produce()” the expression is actually executed and return a real Product. The constructor of Product takes the constructor arg “foo” which is a mock and it executes “f.getBar()”. This invocation is recorded by mockito because this “foo” instance is a mock.

Then when you want to return “mpoo”, mockito raises the exception WrongTypeOfReturnValue saying that the recorded invocation “foo.getBar()” cannot return a Product.

If you want to mock a partial mock, which you should avoid if possible. You need to use the following style for spies, this way Mockito can tell the spy instance to only record the invocation.




Know More

To know more about Junit, Mockito and exception solutions follow below links: