Scrivio Interview library
DebuggingFoundations6 min read · updated 12 November 2026

A test class passes when run alone but fails when run with the whole suite. What are common causes in a Spring Boot project?

When a test passes alone but fails with the suite, another test has changed something they share. In a Spring Boot project the usual suspects are shared mutable static state or singletons, database rows left behind by a test that did not roll back or clean up, a cached Spring application context whose beans another test modified without @DirtiesContext, global settings such as system properties, the default time zone or locale changed by a test, and plain order dependence where a test relies on another having run first.

Why this question is asked

This is one of the most common and most frustrating problems in a growing test suite: the build fails, the developer runs the failing test in the IDE, it passes, and nobody knows what to fix. Interviewers ask it because the answer shows whether we understand what tests share with each other in a Spring project and whether we can debug methodically instead of adding retries. In this answer, we will see why running alone hides the problem, go through the common causes one by one with examples, and finish with a method for finding the guilty test.

1Why Running Alone Hides the Problem

Running one test class alone gives it a clean world: a fresh JVM, an empty static state, a newly created Spring context and a database containing only what the setup inserts. In the full suite, the same class runs in a JVM where hundreds of tests have already run, often reusing the same Spring context and the same database. So the failing test is usually not the broken one. It is the victim of something another test left behind, the polluter, and our job is to find what they share.

2Shared Static State and Singletons

Static fields live as long as the class is loaded, which in a test run usually means the whole run. A test that changes a static cache, a static feature flag holder or a singleton's configuration changes it for every later test.

Java
public final class FeatureFlags {
private static final Map<String, Boolean> FLAGS = new ConcurrentHashMap<>();
public static void set(String name, boolean on) { FLAGS.put(name, on); }
public static boolean on(String name) { return FLAGS.getOrDefault(name, false); }
}
class NewCheckoutTest {
@Test void usesNewFlow() { FeatureFlags.set("new-checkout", true); /* ... */ } // never reset
}
class CheckoutTest {
@Test void usesClassicFlow() {
assertEquals("classic", checkout.flow()); // alone: passes; after NewCheckoutTest: "new"
}
}

The fix is to reset the state in @AfterEach, or better, to replace the static holder with an injected bean so each test controls it explicitly.

3Database Rows Left Behind

Spring's @Transactional on a test rolls back its changes, but only changes made on the test's own thread and transaction. Rows survive when a test is not transactional at all, when the code commits in its own transaction (REQUIRES_NEW, @Async, a message listener), or when a test calls the application over a real HTTP port with @SpringBootTest(webEnvironment = RANDOM_PORT), because the server handles the request on another thread. A later test that counts rows or expects a unique email then fails.

Java
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@Transactional // does not cover the server thread
class RegistrationApiTest {
@Test void registers() {
rest.postForEntity("/users", new NewUser("ada@example.com"), Void.class); // committed by the server
}
}
@DataJpaTest
class UserRepositoryTest {
@Test void startsEmpty() { assertEquals(0, users.count()); } // fails with the suite: 1
}

The fix is explicit cleanup for such tests, for example truncating tables in @AfterEach or with @Sql scripts, or giving each test unique data, such as random emails, so leftovers cannot collide.

4A Cached Spring Context Modified by a Test

The Spring TestContext framework caches application contexts and reuses one context for every test class with the same configuration. That makes suites fast, but it means beans are shared across classes. If a test changes a singleton bean's state, for example replaces a strategy, fills an in-memory cache, or changes a property on a configuration bean, later test classes inherit that change.

Step throughHow a shared context carries state between classes
Spring context cachePricingTestCheckoutTest
get context for config X
new context (cached)
pricing.setStrategy(halfPrice)
get context for config X
same cached context, halfPrice still set
expects full price: fails

6 messages in order. Play them, or step through them one at a time.

When a test genuinely must change the context, @DirtiesContext tells Spring to close the context after the test or class so the next one gets a fresh one, at the cost of a slower suite. Usually better is to avoid mutating beans: reset caches in @AfterEach, use @MockitoBean (in recent Spring versions; older ones used @MockBean) which Spring resets after each test, or keep the changed state in a separate test configuration.

5Global JVM Settings and Order Dependence

Some settings are global for the whole JVM: system properties, the default time zone from TimeZone.setDefault, the default Locale, and environment-like settings stored in statics. A test that sets the time zone to Asia/Tokyo to check a date calculation, and does not restore it, makes later date tests fail by a day. JUnit's @ResourceLock and libraries such as JUnit Pioneer's @DefaultTimeZone and @SetSystemProperty, which restore the value afterwards, help here; or we restore it ourselves in @AfterEach.

Finally there is plain order dependence: a test that only passes because an earlier test created a user or warmed a cache. It passes in the suite and fails alone, the mirror image of our case, and both point to tests that are not independent.

6Finding the Polluting Test

We do not guess; we narrow down. First, read the failure carefully: an unexpected row, a wrong time or a changed bean already points to one of the causes above. Second, reproduce in the suite order, for example by running the package or module containing the test, then cut the set of earlier tests in half repeatedly until the failure appears with just one other class. Third, run the suite in random order with MethodOrderer.Random and ClassOrderer.Random to expose hidden dependencies; the seed printed in the log lets us replay a failing order.

Java
# junit-platform.properties: random order to expose dependencies
junit.jupiter.testmethod.order.default = org.junit.jupiter.api.MethodOrderer$Random
junit.jupiter.testclass.order.default = org.junit.jupiter.api.ClassOrderer$Random
# the seed is logged; set it to replay a failing order (check the exact property name for your version)
junit.jupiter.execution.order.random.seed = 4242

Once we find the pair, the fix goes into the polluter, not the victim: it must clean up after itself. Adding cleanup to the victim only moves the problem.

7Follow-up questions

Would adding @DirtiesContext everywhere fix it?

It may fix context pollution, but it throws away context caching, so a suite that took 4 minutes can take 20. It also does nothing for static state, database rows or JVM settings. It is a targeted tool for the few tests that must change the context, not a general fix.

Why does the failure sometimes depend on the machine?

Because the order of test classes can differ between the IDE, Maven and Gradle, and with parallel execution the interleaving changes from run to run. The pollution was always there; only the order that exposes it changed.

Should flaky tests be retried automatically?

Retries hide the cause and keep the shared state bug in the suite. I would only allow retries temporarily for a quarantined test with an owner and a ticket, while we find the polluter.

8Conclusion

In this answer, we saw that a test failing only in the full suite is usually the victim of state another test left behind. The common causes in Spring Boot projects are static state and singletons, database rows that escaped rollback, beans changed in a cached application context without @DirtiesContext, global settings such as system properties, time zone and locale, and order dependence. We find the polluter by reading the failure, narrowing the set of earlier tests and running in random order, and we fix the polluter rather than the victim.

What to say in the interviewAbout 90 seconds aloud

Open with

If a test passes alone and fails in the suite, something it shares with other tests was changed by one of them, so I look for the polluter rather than the victim.

Then, if they want more

In a Spring Boot project I would check five things. Static state and singletons, like a static feature flag map that one test sets and never resets.

Database rows left behind, because @Transactional only rolls back the test thread's transaction, so anything committed by the server thread in a RANDOM_PORT test, by @Async, or by REQUIRES_NEW stays, and later counts or unique constraints fail.

The cached Spring context: Spring reuses one context for all classes with the same configuration, so if a test changes a bean's state without @DirtiesContext, later classes see it; I would rather reset the state or use @MockitoBean than dirty the context everywhere. Global JVM settings like system properties, the default time zone or locale.

And order dependence, where a test relies on data another test created. To find it, I read the failure for clues, run the module, then bisect the earlier tests until one other class reproduces it, and I run the suite in random order with the seed logged to expose hidden dependencies. Then I fix the polluting test so it cleans up after itself.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
JUnit user guide
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A test class passes when run alone but fails when run with the whole suite. What are...": https://scrivio-interview-library.netlify.app/java/junit/6469085dce/