Tag Archives: junit

Fixing Mockito UnnecessaryStubbingException with JUnit5

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

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
  • else, annotate your test class with :
    @MockitoSettings(strictness = Strictness.LENIENT)
    It will relax the mockito stubbing rules.