Performance: @SpringBootTest for integration tests
This affects the test execution time and resource usage during integration testing, impacting developer feedback speed and CI pipeline duration.
@SpringBootTest(classes = MyServiceConfig.class) public class MyServiceTest { @Autowired private MyService service; @Test void testService() { // test logic } }
@SpringBootTest
public class MyServiceTest {
@Autowired
private MyService service;
@Test
void testService() {
// test logic
}
}| Pattern | Context Load Time | Memory Usage | Test Execution Speed | Verdict |
|---|---|---|---|---|
| Full @SpringBootTest | High (1-3s per test class) | High | Slow | [X] Bad |
| @SpringBootTest with limited config | Medium (0.3-1s) | Medium | Faster | [!] OK |
| Slice test annotations (e.g., @WebMvcTest) | Low (<0.5s) | Low | Fast | [OK] Good |
@SpringBootTest in a Spring Boot project?@SpringBootTest does@SpringBootTest is used for integration tests that need the full app context.@SpringBootTest to start the web environment on a random port?webEnvironment, and the enum value for random port is WebEnvironment.RANDOM_PORT.\@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class MyIntegrationTest {
\@Autowired
private TestRestTemplate restTemplate;
\@Test
void testHelloEndpoint() {
String response = restTemplate.getForObject("/hello", String.class);
System.out.println(response);
}
}/hello endpoint returns "Hello, Spring!".@SpringBootTest with RANDOM_PORT and injects TestRestTemplate, which allows calling the real HTTP endpoint./hello endpoint returns "Hello, Spring!" so the call will return this string and print it.NoSuchBeanDefinitionException for TestRestTemplate. What is the likely cause?\@SpringBootTest
class MyTest {
\@Autowired
private TestRestTemplate restTemplate;
\@Test
void test() {
// test code
}
}@SpringBootTest does not start the web server unless webEnvironment is set, so TestRestTemplate bean is not created.webEnvironment = WebEnvironment.RANDOM_PORT or DEFINED_PORT starts the server and creates the bean.webEnvironment setting to start web server -> Option B@SpringBootTest configuration should you use?WebEnvironment.NONE disables web server startup but loads full context. MOCK uses mock servlet environment, RANDOM_PORT and DEFINED_PORT start real servers.WebEnvironment.NONE.Pass the test and this pattern moves unknown