Skip to content
Latchkey

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.

Spring Boot
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.

src/test/java
@AfterEach
void resetMocks() { Mockito.reset(paymentClient); }

Set stubs per test, not in setup that leaks

  1. Define when(...).thenReturn(...) inside each test that needs it.
  2. Avoid stubbing in a shared static block that persists across the cached context.
  3. Re-run the full suite to confirm order independence.

How to prevent it

  • Reset @MockBean in @AfterEach to avoid cross-test leakage.
  • Keep stubbing local to each test method.
  • Do not rely on test execution order in CI.

Frequently asked questions

What causes "@MockBean leaking across tests"?
Spring reuses the same context (and thus the same @MockBean) across tests; stubs from one test remain unless reset.
How do I fix @MockBean leaking across tests?
Reset the mock in a teardown so each test starts clean even with a shared context.

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card