Video in progress

Strong Middle 🧪 Testing

The tests pass when run alone but fail with the whole suite. How do you investigate?

This is almost always state that "leaked" between tests: a static field, an uncleaned database, a modified bean or a global setting. First I find the order, meaning which test has to run first for the failure to happen, then I isolate that pair and find the leftover state.

📖 Answer

The steps, as I usually go:

  1. From the CI log I get which tests ran before the failing one. In JUnit 5 the order is deterministic but not "obvious"; you can trigger the problem on purpose by running with MethodOrderer.Random.
  2. I search by bisecting: remove half of the earlier tests and run, then the other half. In 3-4 iterations the culprit test turns up.
  3. I run the pair (A then B) on its own and see what A leaves behind.

Common causes:

  • A writes to the database and doesn't clean up; B expects count() == 1;
  • A stubs a mock in a cached Spring bean, and Mockito's reset is automatic only for @MockitoBean: mock beans created by hand aren't reset;
  • A configures the ObjectMapper bean and that setting lives on with the context;
  • a static Clock or feature flag.

The fix is to make B robust (search by an exact ID, don't rely on count) and to make A clean up after itself. I do both: if you fix only one, the next new test falls into the same trap.

As prevention, running the full suite in random order once a week in CI works well.