Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

A TestNG test with @Test(timeOut = 5000) that uses a Spring @Transactional test context sees no rollback, and data from it remains in the database. Explain.

With timeOut, TestNG runs the test method on a different thread from the configuration methods. Spring's test transaction is started in a @BeforeMethod hook on the main thread and bound to that thread through thread locals, so the repository calls in the timeout thread run outside it, use their own transactions or auto-commit, and their data stays. The fix is to remove timeOut from transactional tests and enforce time limits elsewhere, or to manage the transaction explicitly inside the test.

Why this question is asked

This is one of those bugs where every part works and the combination does not. The test class extends Spring's transactional TestNG base class, so every test should roll back. Someone adds timeOut = 5000 to guard against a hang, the test still passes, and a week later the shared test database is full of rows that should not exist. Interviewers like it because the explanation needs two pieces of knowledge, how TestNG implements timeouts and how Spring tracks transactions, and the same root cause appears with security contexts and logging. In this answer, we will recap how Spring rolls back test transactions, reproduce the problem, trace exactly where the transaction gets lost, and go through the fixes.

1A Quick Recap of Spring's Test Transactions

In a Spring test, @Transactional on the test class or method asks the TestContext framework to wrap each test in a transaction and roll it back at the end, so tests leave the database as they found it. With TestNG, we usually get this by extending AbstractTransactionalTestNGSpringContextTests, which registers the right listeners.

The work is done by TransactionalTestExecutionListener. Before each test method it starts a transaction through the transaction manager, and after the method it rolls it back. Spring does not pass the transaction around as a parameter. Instead, it binds it to the current thread with TransactionSynchronizationManager, which keeps the current connection and transaction status in ThreadLocal variables. Any repository or JdbcTemplate call on the same thread finds the transaction there and joins it. A call on another thread finds nothing and behaves as if no test transaction existed.

2Reproducing the Problem

Here is a test that saves an order and checks the count. Without timeOut, the row is rolled back after the test. With timeOut = 5000, the test still passes, but the row remains in the database.

Java
@SpringBootTest
@Transactional
public class OrderRepositoryTest extends AbstractTransactionalTestNGSpringContextTests {
@Autowired OrderRepository orders;
@Test(timeOut = 5000)
public void savesOrder() {
orders.save(new Order("SKU-1", 2));
boolean inTx = TransactionSynchronizationManager.isActualTransactionActive();
System.out.println("in test transaction: " + inTx); // in test transaction: false
assertEquals(orders.count(), 1); // passes on an empty table
}
}
// After the run: SELECT count(*) FROM orders; -- 1, the row was committed

The println is the key piece of evidence. Inside the test method there is no active transaction, even though the class is @Transactional. Removing timeOut and running again prints in test transaction: true, and the table is empty afterwards.

3Tracing Where the Transaction Gets Lost

The Spring base class starts the transaction from a configuration method, a @BeforeMethod hook that TestNG runs on the main test thread. To enforce timeOut, TestNG then runs the test method itself on a separate worker thread and waits for it with a time limit. So the transaction is bound to thread A, and the test code runs on thread B.

On thread B, orders.save() finds no transaction bound to the thread. Spring Data repository methods are transactional by default, so save() starts its own short transaction and commits it immediately. When the test ends, the after-method hook on thread A rolls back the test transaction, which never contained any work. The rollback succeeds, the test passes, and the committed row stays.

Step throughTwo threads, two transactions
TestNG main threadSpring listenerTimeout threadDatabase
@BeforeMethod: beforeTestMethod
begin test transaction (bound to main thread)
run savesOrder() with timeOut = 5000
save(): no transaction on this thread, begin new one
commit the new row
test finished in time
@AfterMethod: afterTestMethod
roll back the empty test transaction

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

The rollback happens on the thread that never did any work.

4The Same Problem With Other Thread-Bound Context

Anything Spring or our code keeps in ThreadLocal variables is affected in the same way. SecurityContextHolder uses a thread-local strategy by default, so a test that sets an authenticated user with @WithMockUser or in a @BeforeMethod sees an anonymous user inside a timeOut method, and security checks fail or, worse, are skipped by code that treats no authentication as a system call. The logging MDC, the map of values such as a request id that log lines include, is also per thread, so log lines from the test method lose their context. Request-scoped beans and locale holders behave the same way.

5Fix 1: Remove timeOut and Enforce Limits Elsewhere

The simplest fix is to take timeOut off transactional tests. Most repository tests do not hang; they fail quickly when something is wrong. To protect the pipeline from a real hang, we put a time limit on the whole CI job or on the Surefire fork with its forkedProcessTimeoutInSeconds setting, which kills a stuck test JVM. When we really want to assert that an operation is fast, we measure it on the same thread and assert on the duration, which does not change threads.

Java
@Test
public void savesOrderQuickly() {
long start = System.nanoTime();
orders.save(new Order("SKU-1", 2));
long ms = (System.nanoTime() - start) / 1_000_000;
assertTrue(ms < 5000, "save took " + ms + " ms"); // same thread, transaction still rolled back
}

Notice that this check is not preemptive: if save() hangs forever, the test hangs too, and the CI job timeout ends it. That is a fair trade, because hangs are rare and a silently committed row breaks other tests every day.

6Fix 2: Manage the Transaction Inside the Test

If a test must keep timeOut, for example because it calls code known to hang under some conditions, it can open and roll back its own transaction on the worker thread with TransactionTemplate.

Java
@Autowired PlatformTransactionManager txManager;
@Test(timeOut = 5000)
public void savesOrderWithinTimeLimit() {
new TransactionTemplate(txManager).executeWithoutResult(status -> {
orders.save(new Order("SKU-1", 2));
assertEquals(orders.count(), 1); // inside the transaction on the worker thread
status.setRollbackOnly(); // nothing is committed
});
}

Now the transaction is started on the same thread as the test code, so the save joins it and the rollback undoes it. This class should not also carry @Transactional, so readers are not misled about which transaction is in charge.

7Follow-up questions

How would you find all the tests affected by this in a large suite?

Search for timeOut in classes that are @Transactional or extend the transactional base class, and add a check to the shared test library: a listener that fails a test when it has a timeOut and its class is transactional. Running a query for leftover rows after the suite in CI also catches any test that commits data, whatever the cause.

Does JUnit Jupiter have the same problem?

Yes, with preemptive timeouts. @Timeout in its default mode runs the test on the same thread and interrupts it, so Spring transactions still work. But assertTimeoutPreemptively, or @Timeout with the separate-thread mode, runs the code on another thread, and Spring's documentation warns that such code does not take part in the test-managed transaction.

Why did the test pass even though the data was committed?

Because the assertions only checked what happened inside the test, and the count was correct for an empty table. The rollback at the end also reported success, since rolling back an empty transaction is not an error. Nothing in the test looks at the database after the rollback, which is why the bug shows up later in other tests.

8Conclusion

In this answer, we saw that Spring binds the test transaction to the thread that started it, in a @BeforeMethod hook, while TestNG runs a timeOut method on a separate worker thread. The repository calls there found no transaction, committed their own, and the final rollback undid nothing. The same applies to the security context and the MDC. We fixed it by removing timeOut from transactional tests and enforcing time limits at the job or fork level, or by managing the transaction with TransactionTemplate inside the test.

What to say in the interviewAbout 90 seconds aloud

Open with

The cause is a thread mismatch. When a TestNG test has timeOut, TestNG runs the test method on a separate worker thread so it can stop waiting after five seconds, while the configuration methods run on the main test thread.

Then, if they want more

Spring's TransactionalTestExecutionListener starts the test transaction from a before-method hook on the main thread, and Spring binds transactions to the current thread through thread locals in TransactionSynchronizationManager.

So the repository calls in the worker thread see no transaction, the repository starts and commits its own, and at the end Spring rolls back the test transaction on the main thread, which is empty. The test passes and the row stays. I would prove it by logging isActualTransactionActive inside the test: it prints false.

The same thing happens with SecurityContextHolder and the MDC, which are also thread-local. My fix is to not use timeOut on transactional tests.

If I need protection against a hang, I set a timeout on the CI job or the Surefire fork, and if I need to check speed, I measure the duration on the same thread and assert on it. If a test really must keep timeOut, it can manage its own transaction with TransactionTemplate inside the method and mark it rollback-only.

I would also add a check after the suite that the test tables are empty, so any committing test is caught.

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.
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 test with @Test(timeOut = 5000) that uses a Spring @Transactional test context...": https://scrivio-interview-library.netlify.app/java/testng/bbfd437658/