when I run mockito test occurs WrongTypeOfReturnValue Exception

JavaMockito

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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.

Solution 3 - Java

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

Solution 4 - Java

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.

Solution 5 - Java

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.

Solution 6 - Java

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

Solution 7 - Java

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

Solution 8 - Java

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

Solution 9 - Java

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

Solution 10 - Java

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.

Solution 11 - Java

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

Solution 12 - Java

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.

Solution 13 - Java

Missing @MockBean on the bean you want to mock

Solution 14 - Java

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

Solution 15 - Java

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

Solution 16 - Java

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.

Solution 17 - Java

Android

In my case, or rather Android project's instrumentation tests:

  • One time, I just needed to remove the build directory (to force rebuild).
  • Another time, computer went out of memory, causing issues to all open Apps, and restarting each App was enough (without need to restart computer).

Maybe there are too many reasons for one single error!
(they should fix this already).

But I hope this helps someone
d= (◕‿↼ )

>Nowadays, because command-line does things better than IDE, >I load command-line created test-result.pb file in IDE later >(after all tests finish).

Solution 18 - Java

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.

Solution 19 - Java

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.

Solution 20 - Java

For my case, it turns out that the type of mocked object is actually an abstract interface, the issue gets resolved after changing the type to some implementation class,

Change

@Mock
private Proxy proxy;

to

@Mock
private ProxyImpl proxy;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionconfused windbellView Question on Stackoverflow
Solution 1 - JavagnaView Answer on Stackoverflow
Solution 2 - JavajuhoautioView Answer on Stackoverflow
Solution 3 - JavaLukeView Answer on Stackoverflow
Solution 4 - JavarogerdpackView Answer on Stackoverflow
Solution 5 - Javanot_johnView Answer on Stackoverflow
Solution 6 - JavaTzafrirView Answer on Stackoverflow
Solution 7 - JavaACVView Answer on Stackoverflow
Solution 8 - JavaihebihebView Answer on Stackoverflow
Solution 9 - JavaYounes El OuartiView Answer on Stackoverflow
Solution 10 - JavadillipView Answer on Stackoverflow
Solution 11 - JavaDHANDAYUTHAPANI MUNISAMYView Answer on Stackoverflow
Solution 12 - JavasimonevertssonView Answer on Stackoverflow
Solution 13 - JavabuddhaView Answer on Stackoverflow
Solution 14 - JavaRotSView Answer on Stackoverflow
Solution 15 - JavaS.DainekoView Answer on Stackoverflow
Solution 16 - JavaDamianView Answer on Stackoverflow
Solution 17 - JavaTop-MasterView Answer on Stackoverflow
Solution 18 - JavaSurasin TancharoenView Answer on Stackoverflow
Solution 19 - JavaOğuzhan SoykanView Answer on Stackoverflow
Solution 20 - Javabrook hongView Answer on Stackoverflow