Scrivio Interview library
DesignIntermediate7 min read · updated 12 November 2026

A TestNG suite for a Spring Boot application extends AbstractTestNGSpringContextTests. Explain how Spring context loading interacts with the TestNG lifecycle and how you keep a 2,000 test suite fast.

AbstractTestNGSpringContextTests plugs Spring's TestContext framework into TestNG: configuration methods marked @BeforeClass(alwaysRun = true) and @BeforeMethod(alwaysRun = true) prepare the context and inject dependencies, and the class implements IHookable so Spring can wrap each test method. The ApplicationContext comes from Spring's context cache, keyed by the test's full configuration, so classes with identical configuration share one context, while any difference in @MockitoBean (or the older @MockBean), properties or profiles creates a new one. A 2,000 test suite stays fast by keeping a few shared configurations, using test slices and plain unit tests where possible, avoiding @DirtiesContext, and watching cache misses in the logs.

Why this question is asked

Spring Boot test suites often start fast and become slow as they grow, and with TestNG the cause is the same as with JUnit: the application context is rebuilt far more often than anyone expects. Each rebuild costs seconds, and in a suite of 2,000 tests those seconds become many minutes. Interviewers ask this design question to see whether we understand how the Spring TestContext framework hooks into TestNG and how the context cache decides when to reuse a context. In this answer, we will recap the TestContext framework, see how it connects to TestNG's lifecycle, look at how the context cache key works, and then design a suite that stays fast, including transactional tests and measuring cache misses.

1A Quick Recap of the Spring TestContext Framework

Spring's TestContext framework is the part of spring-test that loads an ApplicationContext for tests, injects beans into test instances with @Autowired, and manages features such as transactions per test. It is independent of the test framework. A TestContextManager does the work, and small adapters connect it to JUnit Jupiter (the SpringExtension) or to TestNG (the AbstractTestNGSpringContextTests base class).

The expensive part is building the ApplicationContext: scanning classes, creating beans, starting an embedded server or connecting to a database. In a typical Spring Boot service that takes 3 to 15 seconds, so suite speed comes down to how many times it happens.

2How the Base Class Hooks Into TestNG

TestNG has no extension model like Jupiter's, so Spring uses a base class with configuration methods and a hook. When a test class extends AbstractTestNGSpringContextTests, TestNG finds the base class's annotated methods and runs them as part of its normal lifecycle.

Java
@SpringBootTest
class OrderApiTest extends AbstractTestNGSpringContextTests {
@Autowired OrderService orders; // injected by Spring before the first test
@Test public void createsOrder() { ... }
}
// What runs, simplified:
// @BeforeClass(alwaysRun = true) springTestContextBeforeTestClass
// @BeforeClass(alwaysRun = true) springTestContextPrepareTestInstance -> get context from cache, inject @Autowired fields
// @BeforeMethod(alwaysRun = true) springTestContextBeforeTestMethod -> e.g. start a test transaction
// run(IHookCallBack, ITestResult) -> IHookable: Spring wraps the test method call
// @AfterMethod(alwaysRun = true) springTestContextAfterTestMethod -> e.g. roll back
// @AfterClass(alwaysRun = true) springTestContextAfterTestClass

alwaysRun = true matters here. When a run selects only some groups, TestNG would otherwise skip configuration methods that are not in those groups, and the test would run without a context. The IHookable interface lets Spring run code around each test method invocation, so it can apply test execution listeners at the right moment.

One consequence of TestNG's model is worth noticing: TestNG uses one instance per test class, so injection happens once per class in the prepare step, and the same injected beans are used by every method of that class.

3The Context Cache and Its Key

Spring does not build a new context for every test class. It keeps built contexts in a static cache for the life of the test JVM, and before building one it computes a key from the test class's merged configuration: the configuration classes or locations, active profiles, property sources and inline properties, context initialisers and customisers, and the parent context. If another class produces the same key, it gets the cached context in milliseconds.

The catch is that many small differences change the key. A class with @ActiveProfiles("test") and one with @ActiveProfiles("test", "kafka") get different contexts. A @TestPropertySource with one extra property creates a new context. And each distinct set of @MockitoBean or @MockBean fields changes the key too, because replacing a bean with a mock changes what the context contains. In large suites, the mock beans are usually the biggest source of new contexts. @MockitoBean is the replacement for @MockBean from Spring Framework 6.2; @MockBean was deprecated in Spring Boot 3.4.

Step throughHow a test class gets its context
  1. Merge the class's test configurationclasses, profiles, properties, mock beans
  2. Compute the cache key
  3. Key already in the cache?
    YesReuse it: millisecondsNoBuild a new context: seconds
  4. Store it in the cachedefault maximum 32 contexts, least recently used evicted
  5. Inject @Autowired fields into the test instance

5 steps in order. Play them, or step through them one at a time.

Every distinct key costs a full context start.

4Designing a 2,000 Test Suite That Stays Fast

The first design rule is to have very few distinct configurations. I would define two or three base classes, for example one for full application tests, one for web layer tests and one for repository tests, each with fixed profiles, properties and a fixed set of mock beans for external systems such as the payment provider and the message broker. Individual test classes extend one of these and do not add their own @MockitoBean fields or properties. If a test needs different behaviour from a mock, it stubs the shared mock in its own setup and resets it afterwards; Spring resets @MockitoBean mocks after each test method by default.

The second rule is to push tests down. Most of 2,000 tests should not need Spring at all: domain logic tested with plain TestNG classes and new, which run in milliseconds. Where Spring is needed, a slice such as @WebMvcTest or @DataJpaTest starts only part of the application, which is faster than @SpringBootTest. A healthy shape might be 1,500 plain unit tests, 400 slice tests across a handful of configurations and 100 full context tests sharing one configuration.

The third rule is to avoid @DirtiesContext. It tells Spring that a test changed the context in a way that cannot be undone, so Spring closes the context and removes it from the cache, and the next class with the same key builds it again from scratch. Used on ten classes, it can add a minute or more. Tests should clean up their own state instead, for example by rolling back transactions.

5Transactional Tests and Measuring Cache Misses

For tests that touch the database, AbstractTransactionalTestNGSpringContextTests extends the base class with transaction management: each test method runs in a transaction that is rolled back at the end by default. That keeps tests independent without dirtying the context. It needs a DataSource and a transaction manager in the context, and it is useful to remember that code running in other threads, or committing in a REQUIRES_NEW transaction, is not covered by that rollback.

Finally, we measure. The cache size is limited by spring.test.context.cache.maxSize, 32 by default, set as a JVM system property or in a spring.properties file. If a suite has more distinct configurations than that, contexts are evicted and rebuilt, which is a second, hidden cost. Turning on debug logging for org.springframework.test.context.cache prints cache statistics, including hit and miss counts. Counting how many contexts were built in a run is the single most useful number: a 2,000 test suite with five contexts is fast, and the same suite with 80 contexts is slow, whatever else we optimise.

Java
# src/test/resources/logback-test.xml or application properties for tests
logging.level.org.springframework.test.context.cache=DEBUG
// Spring test ApplicationContext cache statistics:
// [DefaultContextCache@5b1f size = 5, maxSize = 32, parentContextCount = 0,
// hitCount = 312, missCount = 5] <- 5 contexts built for the whole run

6Follow-up questions

Why is @DirtiesContext expensive?

Because it closes the current application context and removes it from the cache, so the next test class that needs the same configuration must build it again, which takes seconds for a Spring Boot application. With classMode AFTER_EACH_TEST_METHOD it is even worse, rebuilding after every method. In a large suite, a few uses can add minutes, so it should be a last resort after trying to reset state another way.

Do @MockitoBean mocks always create a new context?

A new combination of mocked beans creates a new cache key, so it builds a new context the first time. Classes that declare exactly the same mocks share a context. That is why moving common mocks into a shared base class or configuration keeps the number of contexts low.

7Conclusion

In this answer, we saw how AbstractTestNGSpringContextTests connects Spring's TestContext framework to TestNG through @BeforeClass and @BeforeMethod configuration methods marked alwaysRun = true and the IHookable interface. Contexts come from a cache keyed by the merged configuration, so differences in mock beans, properties or profiles create new contexts. A 2,000 test suite stays fast with a few shared configurations, plain unit tests and slices, transactional rollback instead of @DirtiesContext, and by watching the cache size and miss count.

What to say in the interviewAbout 90 seconds aloud

Open with

When a TestNG class extends AbstractTestNGSpringContextTests, it inherits configuration methods that connect Spring's TestContext framework to TestNG's lifecycle. They are @BeforeClass and @BeforeMethod methods with alwaysRun set to true, so they run even when only some groups are selected, plus matching after methods, and the class implements IHookable so Spring can wrap each test method.

Then, if they want more

In the before-class step, Spring gets the application context and injects the autowired fields; since TestNG uses one instance per class, that happens once per class. The key to speed is the context cache. Spring computes a key from the merged test configuration: config classes, profiles, properties and mock beans.

Classes with the same key share one context; any difference, especially a different set of @MockitoBean or @MockBean fields, builds a new one, which costs seconds.

So for 2,000 tests I would keep two or three shared base configurations with fixed profiles and a fixed set of mocks, make most tests plain unit tests without Spring, use slices like @WebMvcTest where I need part of the context, and avoid @DirtiesContext because it throws away the context and forces a rebuild.

For database tests, AbstractTransactionalTestNGSpringContextTests rolls back each test. And I would turn on debug logging for the context cache and watch the miss count and the maxSize, 32 by default.

About this answer

Last updated
12 November 2026
Versions it names
Spring Boot 3.4, Spring Framework 6
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.
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 TestNG suite for a Spring Boot application extends AbstractTestNGSpringContextTests....": https://scrivio-interview-library.netlify.app/java/testng/b92a30c527/