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


UnnecessaryStubbingException is runtime and sub class of MockitoException. Mockito JUnit Runner triggers UnnecessaryStubbingException only when none of the test methods use the stubbings. This means that it is ok to put default stubbing in a ‘setup’ method or in test class constructor. That default stubbing needs to be used at least once by one of the test methods.

Constructors

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

Example

//code test:
 String result = translator.translate("Saurabh");

//Mock:
// <- stubbing used during code execution
 when(translator.translate("Saurabh")).thenReturn("Gupta");
// <- stubbing never used
when(translator.translate("Gaurav")).thenReturn("Gupta");

Solutions

It is highly recommended to remove unused stubbings to keep the codebase clean. You can opt-out from detecting unused stubbing using MockitoJUnitRunner.Silent() or MockitoRule.silent() (when you are using Mockito JUnit rules.

References

https://static.javadoc.io/org.mockito/mockito-core/2.6.5/org/mockito/exceptions/misusing/UnnecessaryStubbingException.html

Know More

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

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s