Video in progress
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:
- 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. - 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.
- I run the pair (
AthenB) on its own and see whatAleaves behind.
Common causes:
Awrites to the database and doesn't clean up;Bexpectscount() == 1;Astubs a mock in a cached Spring bean, and Mockito's reset is automatic only for@MockitoBean: mock beans created by hand aren't reset;Aconfigures theObjectMapperbean and that setting lives on with the context;- a static
Clockor 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.
Sign up to mark studied questions and save your progress.