Fix Mockito UnnecessaryStubbingException in JUnit 5
Fix Mockito's UnnecessaryStubbingException by removing dead stubs, moving setup into the tests that use it and using lenient stubs only where they belong.

A test that passed yesterday fails today without any production change, and the failure arrives after the test body has finished:
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):
1. -> at dev.javahacks.OrderServiceTest.setUp(OrderServiceTest.java:28)
Please remove unnecessary stubbings or use 'lenient' strictness. More info: javadoc for UnnecessaryStubbingException class.MockitoExtension runs with strict stubs. After the test, Mockito checks that every when(...) was exercised. The failure says line 28 stubbed something nobody called. The testing approach this protects is in a practical Java testing strategy, and the extension model in the JUnit 5 handbook.
What the failure is telling you
A stub nobody calls is code that does nothing, and it often marks a test that is not testing what its name claims. A test called appliesDiscountForGoldCustomers that stubs customerRepository.findById and never reaches the discount code is passing for the wrong reason. Look at the unused stub first and ask why the code did not call it. Often the answer is a branch that returns early.
Fix 1: delete the stub
If the code no longer needs the call, remove the stub. This is the correct fix more often than people expect: refactorings leave stubs behind, and the strictness check is how you find them.
Fix 2: move shared setup into the tests that need it
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
@Mock CustomerRepository customers;
@Mock PaymentGateway gateway;
@InjectMocks OrderService service;
@BeforeEach
void setUp() {
when(customers.findById(1L)).thenReturn(Optional.of(new Customer(1L, "ana"))); // not every test uses this
}
}A stub in @BeforeEach applies to every test, and the tests that never look up customer 1 fail. Move the stub into each test that needs it, or into a helper method the test calls:
private void givenCustomerExists() {
when(customers.findById(1L)).thenReturn(Optional.of(new Customer(1L, "ana")));
}Fix 3: lenient for the one that is genuinely shared
@BeforeEach
void setUp() {
lenient().when(customers.findById(1L)).thenReturn(Optional.of(new Customer(1L, "ana")));
}lenient() exempts that single stub from the check. Use it for a default that most tests need and a few skip. If more than a couple of stubs need it, the class is probably testing too many things and wants a split.
Fix 4 (last resort): relax the class
@MockitoSettings(strictness = Strictness.LENIENT)This turns the safety net off for the class. It silences the exception and the information it carried.
The cousin: PotentialStubbingProblem
When strict stubs see a call to a stubbed method with different arguments than the stub, they report it:
org.mockito.exceptions.misusing.PotentialStubbingProblem:
Strict stubbing argument mismatch. Please check:
- this invocation of 'findById' method:
customers.findById(2L);
- has following stubbing(s) with different arguments:
1. customers.findById(1L);It means the code asked for customer 2 and the test stubbed customer 1, usually a typo or an id that changed. Fix the argument in the test, or use any() when the value does not matter.
Reproduce it in thirty lines
Seeing the failure once makes every later occurrence easier to read. The test below stubs two methods of a directory, but the class under test uses only one of them. It runs on Mockito 5.20.0 and JUnit 6.0.0 with the console launcher, with no Spring involved.
@ExtendWith(MockitoExtension.class)
class GreeterTest {
interface Directory { String nameOf(long id); String emailOf(long id); }
static class Greeter {
private final Directory directory;
Greeter(Directory directory) { this.directory = directory; }
String greet(long id) { return "Hello, " + directory.nameOf(id); }
}
@Mock Directory directory;
@Test
void greetsByName() {
when(directory.nameOf(7L)).thenReturn("Ada");
when(directory.emailOf(7L)).thenReturn("[email protected]"); // never used by Greeter
assertEquals("Hello, Ada", new Greeter(directory).greet(7L));
}
}greetsByName() ✘
Unnecessary stubbings detected.
Clean & maintainable test code requires zero unnecessary code.
Following stubbings are unnecessary (click to navigate to relevant line of code):
1. -> at GreeterTest.greetsByName(GreeterTest.java:25)
Please remove unnecessary stubbings or use 'lenient' strictness. More info: javadoc for UnnecessaryStubbingException class.The assertion on the greeting passed. The failure comes from MockitoExtension.afterEach, which compares the stubbings the test set up with the ones the code under test actually called. The number in the message, GreeterTest.java:25, is the line of the unused when(...), and that is where the fix goes. Read the line number first: it removes the guessing that makes this error feel mysterious.
Why the check exists
An unused stub is either leftover from a refactoring or evidence that the test no longer exercises the path it claims. If emailOf was once called by greet and a change removed the call, the stub documents behaviour that no longer exists, and the reader of the test is misled about what the class does. Strict stubs turn that drift into a failure at the moment it happens, not a year later.
That is also the reason to be careful with lenient(). It is the right answer for a small number of cases, and the wrong answer when used to make a red build green. Before reaching for it, ask what the stub says about the production code. If the answer is "nothing any more", delete the stub.
A stub used only on some paths
The harder case is a stub that one test needs and another does not, because the production method has branches. A shared @BeforeEach that stubs everything fails the tests that take the other branch. Giving each test its own stubbing keeps it honest and readable, and a small helper method removes the repetition without hiding the setup:
private void userExists(long id, String name) {
when(directory.nameOf(id)).thenReturn(name);
}
@Test
void greetsKnownUser() {
userExists(7L, "Ada");
assertEquals("Hello, Ada", greeter.greet(7L));
}
@Test
void rejectsNegativeIds() {
assertThrows(IllegalArgumentException.class, () -> greeter.greet(-1L));
verifyNoInteractions(directory);
}The second test needs no stub at all, and verifyNoInteractions states the actual requirement: the directory must not be called for an invalid id. A check of that shape protects the behaviour better than a stub that happens not to fire.
What the Spring variants look like
With @MockitoBean in a Spring Boot test the stubs live in a Spring managed context, and the strictness check does not run, because the Mockito extension is not the one managing the mocks. A test that mixes @ExtendWith(MockitoExtension.class) and a Spring context will see strict checks only on mocks created by @Mock. When a failure appears only after someone adds MockitoExtension to a class that used to pass, this is the reason: the stubs were always unused, and nothing was looking.
If the failure names a stub in a base class or a shared fixture, check which tests inherit it. Moving such a stub into a method that only the tests needing it call is nearly always a smaller change than marking it lenient, and the result is a base class that no longer says more than the tests use.
Make strictness a project setting, not an accident
Many teams hit this error first when they upgrade, because the extension's default is strict. Decide the policy once and write it down. The configuration that matches the default is explicit on the class, which also tells a new reader that the behaviour is intended:
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.STRICT_STUBS)
class OrderServiceTest { /* ... */ }Keep STRICT_STUBS for new code. For an old class with hundreds of tests, set Strictness.LENIENT on that class only, with a comment naming the ticket that removes it, and fix the unused stubs a file at a time. Counting the files still marked lenient is an honest measure of how much dead test setup remains.
Where this does not apply
If you use the Spring @MockitoBean, the strictness rules differ: Spring's mocks are not checked by MockitoExtension unless you add it. If you use plain Mockito.mock without the extension, strictness is off by default; opt in with MockitoSession. The Spring side of the same discipline is in Failed to load ApplicationContext. The Mockito documentation on strictness lists the three levels, and the [MockitoExtension page](https://javadoc.io/doc/org.mockito/mockito-junit-jupiter/latest/org/mockito/junit/jupiter/MockitoExtension.html) describes the JUnit 5 integration.


