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.
- UnnecessaryStubbingException(String message) : Will throw exception with message.
//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");
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.
To know more about Junit, Mockito and exception solutions follow below links: