Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What does @SpringBootTest do and when should you use it? @SpringBootTest क्या करता है और इसका उपयोग कब करना चाहिए?

Answer

@SpringBootTest bootstraps the complete Spring application context for a test, the same way the real application would start, including all auto-configuration, beans, and (optionally) an embedded web server via webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT. This makes it the go-to annotation for true end-to-end integration tests.

Because it loads the entire context, @SpringBootTest is significantly slower than a sliced test like @WebMvcTest or a plain unit test, and Spring caches the context across test classes with identical configuration to reduce repeated startup cost. It should be reserved for tests that genuinely need the full wiring — most tests are better served by a narrower slice annotation or Mockito-based unit tests.

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class OrderApplicationTests {
    @Autowired private TestRestTemplate restTemplate;

    @Test
    void createOrder_returns201() {
        ResponseEntity<Order> response = restTemplate.postForEntity("/api/orders", request, Order.class);
        assertEquals(HttpStatus.CREATED, response.getStatusCode());
    }
}

@SpringBootTest टेस्ट के लिए पूरा स्प्रिंग एप्लिकेशन कॉन्टेक्स्ट बूटस्ट्रैप करता है, ठीक वैसे ही जैसे वास्तविक एप्लिकेशन शुरू होता है, जिसमें सभी ऑटो-कॉन्फिगरेशन, बीन्स, और वैकल्पिक रूप से एक एम्बेडेड वेब सर्वर शामिल होता है। यह इसे सच्चे एंड-टू-एंड इंटीग्रेशन टेस्ट के लिए प्रमुख एनोटेशन बनाता है।

पूरा कॉन्टेक्स्ट लोड करने के कारण, @SpringBootTest, @WebMvcTest जैसे स्लाइस्ड टेस्ट या सामान्य यूनिट टेस्ट से काफी धीमा होता है, और स्प्रिंग समान कॉन्फिगरेशन वाले टेस्ट क्लासेज़ में कॉन्टेक्स्ट को कैश करता है।

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class OrderApplicationTests {
    @Autowired private TestRestTemplate restTemplate;

    @Test
    void createOrder_returns201() {
        ResponseEntity<Order> response = restTemplate.postForEntity("/api/orders", request, Order.class);
        assertEquals(HttpStatus.CREATED, response.getStatusCode());
    }
}

Was this answer clear?