Video in progress

Strong Middle 🧪 Testing

How do MockMvc, WebTestClient and TestRestTemplate on RANDOM_PORT differ, and how does that affect transactions?

MockMvc / WebTestClient / TestRestTemplate / RestClient — Server: none (mock servlet) / mock or real / real (RANDOM_PORT); Thread: the test thread / depends / a server pool thread; Filters, serialization: yes / yes / yes, with real HTTP; Effect of the test's @Transactional: reaches the controller / reaches it in mock…

📖 Answer

MockMvc WebTestClient TestRestTemplate / RestClient
Server none (mock servlet) mock or real real (RANDOM_PORT)
Thread the test thread depends a server pool thread
Filters, serialization yes yes yes, with real HTTP
Effect of the test's @Transactional reaches the controller reaches it in mock mode doesn't reach it

This is where many people slip in interviews: putting @Transactional on a RANDOM_PORT test and thinking "the test cleans up after itself" is a mistake. The server commits the request in its own transaction, while the test rolls back its own empty one. Later tests see garbage.

There's a reverse trap too: in a MockMvc test, because the test transaction is open, lazy loading errors and errors that depend on open-in-view stay invisible.

How I choose:

  • controller contract, validation, security: @WebMvcTest + MockMvc;
  • the whole stack, HTTP client settings, gzip, real Tomcat behavior: RANDOM_PORT + cleanup in @AfterEach;
  • a WebFlux app: WebTestClient.

Spring Boot 3.2+ introduced RestClient, and TestRestTemplate still works; in new code I often write a helper based on RestClient.