Spring Boot @MockBean state leaking between tests in CI
Spring caches the application context across tests, so a @MockBean is reused. If a test does not reset its stubs or verifications, they leak into later tests, producing failures that depend on execution order (common when CI parallelizes differently).
What this error means
A test passes alone but fails in the full CI run with unexpected stubbed values or "Wanted but not invoked" verifications, changing with test order.
org.mockito.exceptions.verification.WantedButNotInvoked: Wanted but not invoked:
paymentClient.charge(...);
However, there were other interactions with this mock:Common causes
The mock is shared via the cached context
Spring reuses the same context (and thus the same @MockBean) across tests; stubs from one test remain unless reset.
No reset between tests
Without reset(...) or Mockito's per-method reset, interactions accumulate and later verifications see stale calls.
How to fix it
Reset mocks between tests
Reset the mock in a teardown so each test starts clean even with a shared context.
@AfterEach
void resetMocks() { Mockito.reset(paymentClient); }Set stubs per test, not in setup that leaks
- Define
when(...).thenReturn(...)inside each test that needs it. - Avoid stubbing in a shared static block that persists across the cached context.
- Re-run the full suite to confirm order independence.
How to prevent it
- Reset
@MockBeanin@AfterEachto avoid cross-test leakage. - Keep stubbing local to each test method.
- Do not rely on test execution order in CI.