Quick revision
The short answer
The test's transaction belongs to the test thread only. With RANDOM_PORT, the HTTP request is handled by an embedded server thread that takes its own connection, runs its own transaction and commits, so the test's rollback has nothing to undo. We clean up explicitly instead, by truncating tables, deleting by the test's own ids, or using a fresh schema, while MockMvc tests still roll back because MockMvc runs the controller on the test thread.
What to remember
In this answer, we saw that a test-managed transaction lives in thread-local storage on the test thread. With RANDOM_PORT, the request is handled on a server worker thread, which starts its own transaction on its own connection and commits it, so the test's rollback undoes nothing. MockMvc calls the application on the test thread and joins the transaction, so rollback works there, with the caveat that the code then behaves a little differently from production. For real HTTP tests we clean up explicitly, by truncating, deleting by the test's own ids or using a fresh schema, and choose based on whether tests run in parallel.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The test's transaction belongs to the test thread only. With RANDOM_PORT, the HTTP request is handled by an embedded server thread that takes its own connection, runs its own transaction and commits, so the test's rollback has nothing to undo. We clean up explicitly instead, by truncating tables, deleting by the test's own ids, or using a fresh schema, while MockMvc tests still roll back because MockMvc runs the controller on the test thread.
Why this question is asked
Teams often add @Transactional to a full @SpringBootTest because it worked so well in their @DataJpaTest classes: each test rolled back and the database stayed clean. Then rows start piling up between tests, counts drift, and tests pass alone but fail together. Interviewers ask this question because the answer shows whether we understand how Spring binds a transaction to a thread, and that knowledge explains a whole family of surprises in tests and in production. In this answer, we will recap how test-managed transactions work, reproduce the problem, follow the request across threads to see why nothing rolls back, compare it with MockMvc, and then go through the cleanup options.
1A Quick Recap of Test-Managed Transactions
When a test class or method is annotated with @Transactional, Spring's TransactionalTestExecutionListener starts a transaction before each test method and rolls it back afterwards. The transaction is real: it takes a connection from the pool, and Spring stores that connection and the transaction state in thread-local storage, through a class called TransactionSynchronizationManager. Thread-local storage means each thread sees its own copy of the value.
That detail is the whole story. Any repository call made on the same thread finds the connection in thread-local storage and joins the test's transaction, so its changes disappear at rollback. Code running on any other thread finds nothing there, so it starts its own transaction on its own connection, exactly as it would in production.
2Reproducing the Problem
Here is a test that creates an order through the real HTTP API and expects the table to be clean again for the next test.
The second test fails only when it runs after the first. The order created over HTTP survived the rollback of the first test. If we log TransactionSynchronizationManager.isActualTransactionActive() and the thread name in the controller, we see true on a thread named something like http-nio-auto-1-exec-1, and the test method runs on the main test thread. Two threads, two transactions.
3Following the Request Across Threads
With RANDOM_PORT, Spring Boot starts a real embedded server, Tomcat by default, on a free port. TestRestTemplate sends a real HTTP request over a socket. Tomcat receives it on one of its worker threads and passes it to the DispatcherServlet, which calls our controller and service on that worker thread.
When the service method's @Transactional proxy runs, it looks in thread-local storage on the worker thread, finds no transaction, and starts a new one with a fresh connection from the pool. The insert happens, the service method returns, and the proxy commits. The response goes back over the socket. Meanwhile the test's own transaction, on the test thread, has done nothing at all. At the end of the test it rolls back, which discards nothing, because the committed row was never part of it.
8 messages in order. Play them, or step through them one at a time.
The rollback belongs to the test thread; the server thread already committed.
Notice the reverse effect too. If the test saves a customer in its own transaction before calling the API, that row is not committed, so the server thread cannot see it and the API answers 404. Developers sometimes 'fix' that by removing @Transactional on one test, which is the right instinct for the wrong reason.
4Why MockMvc Tests Do Roll Back
With the default MOCK web environment and MockMvc, there is no server and no socket. MockMvc calls the DispatcherServlet directly, as a method call, on the test thread. The service's @Transactional proxy looks in thread-local storage, finds the test's transaction, and joins it. At the end, the rollback undoes everything the controller did.
But there is a catch. Because the controller runs inside the test's transaction, it behaves differently from production. Lazy loading works in the view where production would throw LazyInitializationException, and constraint violations may not appear until a flush that never comes. So a rolled-back MockMvc test is convenient, but we should remember it is a slightly different world.
5Cleaning Up Explicitly
For tests that go through a real server, we remove @Transactional and clean up on purpose. There are three common ways, and the right one depends on how the tests run.
Truncating is the easiest and leaves nothing behind, but it wipes every test's data, so it breaks as soon as tests run in parallel against the same database. Deleting by the test's own ids, such as a unique customer or tenant id, is safe in parallel and also makes assertions cleaner, because the test can count only its own rows. A fresh schema or database per test class gives the strongest isolation at the price of running migrations more often. In every case, reference data that the migrations insert should stay untouched.
6Follow-up questions
Would @Commit or @Rollback(false) change anything here?
Not for the HTTP part. Those annotations only control what happens to the test thread's transaction. The server thread's transaction commits regardless, because it is an ordinary transaction in the application. They matter for data the test itself wrote on the test thread.
Does the same problem happen with @Async or Kafka listeners?
Yes, for the same reason. Any work handed to another thread, such as an @Async method, a scheduled task, a message listener or a CompletableFuture on a pool, does not see the test's thread-local transaction. It runs and commits in its own transaction, so the test must clean up its data explicitly and wait for the other thread with something like Awaitility.
Is WebTestClient against a running server any different?
No. When WebTestClient is bound to a running server, it also sends real HTTP and the request is handled on a server thread. Only the mock-bound variants, which call the application in-process on the calling thread, can join the test transaction.
7Conclusion
In this answer, we saw that a test-managed transaction lives in thread-local storage on the test thread. With RANDOM_PORT, the request is handled on a server worker thread, which starts its own transaction on its own connection and commits it, so the test's rollback undoes nothing. MockMvc calls the application on the test thread and joins the transaction, so rollback works there, with the caveat that the code then behaves a little differently from production. For real HTTP tests we clean up explicitly, by truncating, deleting by the test's own ids or using a fresh schema, and choose based on whether tests run in parallel.
Open with
The reason is that Spring's test transaction is bound to the test thread. The transactional test listener starts a transaction and stores the connection in thread-local storage through TransactionSynchronizationManager, and only code on that thread joins it.
Then, if they want more
With RANDOM_PORT there is a real Tomcat and the test sends a real HTTP request, so the controller and service run on a Tomcat worker thread. The service's @Transactional finds no transaction there, opens its own on a different connection, and commits. When the test ends, it rolls back its own transaction, which never contained those rows.
It also works the other way: rows the test inserted but did not commit are invisible to the server, which is a common cause of 404s in these tests.
MockMvc is different, because it calls the DispatcherServlet directly on the test thread, so the controller joins the test transaction and rollback works, though lazy loading and flushing then behave differently from production. So for real HTTP tests I remove @Transactional and clean up explicitly. If tests run sequentially, truncating the tables after each test is simplest.
If they run in parallel, I give each test unique ids, like a random customer or tenant id, delete only those rows and filter assertions by them. For strong isolation a fresh schema per class also works.
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, Mockito documentation
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 @SpringBootTest with webEnvironment = RANDOM_PORT is annotated @Transactional, yet...": https://scrivio-interview-library.netlify.app/java/integration-testing/8708d86263/