Tag Archives: mockito

Fixing Mockito UnnecessaryStubbingException with JUnit5

After upgrading to JUnit 5, you may bump into some unit tests now failing with the following error :

org.mockito.exceptions.misusing.UnnecessaryStubbingException: 
Unnecessary stubbings detected.
Clean & maintainable test code requires zero unnecessary code.
Following stubbings are unnecessary (click to navigate to relevant line of code):...

JUnit 5 is tricter regarding stubbing. As explained in the error message, unnecessary stubbing is not a good practice. It usually results from copy and paste, and creates confusion about the tested behaviour. In such a situation, you just want to remove the unnecessary stubbing.

However, there are some cases when you’d like a less strict approach. For example, when you use a helper method that does some mocking that is required by most of the cases, but not all. Than you have to choices :

  • instead of mocking directly with “when(…).then(…)”, prefix the call with lenient(). Ex
    lenient().when(oauth.getAuthorities()).thenReturn(authorities);
  • else, annotate your test class with :
    @MockitoSettings(strictness = Strictness.LENIENT)
    It will relax the mockito stubbing rules.

Mockito : how to mock method return value based on argument ?

When using mockito to mock some methods behaviour, you may want to change your mocked method return value based on an argument value.

This is not obvious, but quite simple to achieve, thanks to this SO post. The following example show how to mock a call to the myMethod() function by returning the first string parameter.

when(mockObject.myMethod(anyString()))
     .thenAnswer(invocation -> invocation.getArgument(0, String.class));