Explain Codes LogoExplain Codes Logo

When I run mockito test occurs WrongTypeOfReturnValue Exception

java
mockito
testing
best-practices
Anton ShumikhinbyAnton Shumikhin·Nov 6, 2024
TLDR

Need a quick solution to the Mockito WrongTypeOfReturnValue Exception? Make sure your thenReturn() value matches the return type of the mocking method. Specifically, if it's supposed to return a List<String>, then ensure to provide a List<String>, not a String or another type.

// It's the signature move, but make sure to get it right! when(mockedObject.expectedMethod()).thenReturn(correctTypeValue);

Pay attention to correctTypeValue — it should be the exact type that expectedMethod() should return. Otherwise, Mockito will give you a red card, aka the exception.

To dodge this, consider switching to the less-loved sibling, the doReturn().when():

// It's less stylish, but completes the job just as good! doReturn(correctTypeValue).when(mockedObject).expectedMethod();

The Power of Precise Mocking: doReturn().when()

Why consider doReturn().when() over the chic and sassy when().thenReturn()? Well, doReturn().when() can ward off the WrongTypeOfReturnValue Exception because it's like a type-ninja. It bypasses the type checking of the thenReturn() argument, making it a life-saver in complex scenarios. Especially with overloaded methods, where it handles unchecked or ambiguous match warnings like a pro.

Debugging: Your Best Friend

Probably the best debugging tip given to mankind - ensure your method is public and accessible. Here's the fact: Mockito, like you and me, can't see through walls or peek into final or private methods. It needs proper access, otherwise, it stumbles and you get an exception. So, be stouthearted and dissect that stack trace. It's your roadmap to the core problem.

A Thread to Be Weary Of

Testing is often a tranquil sea but occasionally the tides rise with a storm: multi-threading! It brings along its troupe of subtle bugs. If multiple threads scramble around your mocks, they could end up losing their state, leading to unexpected return types.

Return type issues: The What, Why & How

Mind the Return Types

Keep your eyes wide open for your method return types. Easy to miss them, but if you do, you've got a problem. Remember, Mockito is as strict with return types as your math teacher with homework.

The Perils of Non-mocks

Beware of the non-mock "Trojan horse". Real instances get mixed up in tests and if a non-mock object decides to return a value, you're in for a ride. Always make sure that only mocks are in charge of returning values.

Arm Yourself with Knowledge

The internet is teeming with resources. Leverage them. The more you understand, the faster you resolve errors. And you get fewer hair-pulling moments during test debugging.