What @SpringBootTest Does
Fast recall
Quick revision
Core answer
Basic understanding of what @SpringBootTest actually does under the hood and the cost it incurs.
Assuming it starts every bean, database, server, and external connection, or that its environment is automatically identical to production.
Mention webEnvironment parameter options—MOCK, RANDOM_PORT, DEFINED_PORT, NONE—and context caching between tests.
Interview-ready guide
Interview answer
@SpringBootTest creates a Boot ApplicationContext through SpringApplication. It can discover the main Boot configuration and apply eligible component scanning and auto-configuration. The exact beans and resources still depend on the test's profiles, properties, web environment, imports, exclusions, and bean overrides, so it is not automatically the same as production. MOCK is the default and opens no server port; RANDOM_PORT and DEFINED_PORT start a server, while NONE creates a non-web context. Spring can reuse contexts with the same TestContext cache key in the same process. I use this annotation when broad Boot wiring is part of the requirement, not for isolated Java logic.
What @SpringBootTest Does
Direct Answer
@SpringBootTest builds a Boot ApplicationContext from the selected configuration, applies the active profiles and properties, and creates the beans required by that context. It does not guarantee a production-identical environment or a connection to every external system; test configuration, mocks, disabled auto-configuration, and the chosen webEnvironment can all change what starts.
Code Example
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class OrderIntegrationTest {
@Autowired private TestRestTemplate restTemplate; // real HTTP client
@Autowired private OrderRepository orderRepository; // real repository
@Test
void shouldCreateOrderEndToEnd() {
var request = new CreateOrderRequest("Laptop", 1500.0);
var response = restTemplate.postForEntity("/orders", request, Order.class);
assertEquals(HttpStatus.CREATED, response.getStatusCode());
var savedOrder = orderRepository.findById(response.getBody().getId());
assertTrue(savedOrder.isPresent()); // verifies database persistence
}
}
Common Mistakes & Pitfalls
- Using @SpringBootTest for isolated logic: A broad context adds setup without improving a test whose requirement is a local calculation.
- Confusing MOCK with a server: The default mode opens no HTTP port; use RANDOM_PORT or DEFINED_PORT for a client that makes real network calls.
- Assuming production equivalence: Test profiles, properties, doubles, exclusions, embedded infrastructure, and environment differences can all change behavior.
Check your understanding
Answer these without looking back at the article.
- What is @DirtiesContext and when should you use it?
- How does @SpringBootTest find the main application class?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.