Subjects

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

What is the difference between unit testing and integration testing in Spring Boot? स्प्रिंग बूट में यूनिट टेस्टिंग और इंटीग्रेशन टेस्टिंग में क्या अंतर है?

Answer

Unit testing verifies a single class or method in complete isolation, with all its dependencies replaced by mocks (using Mockito), so the test runs fast and doesn't load any Spring context. Integration testing verifies how multiple components work together — controller, service, repository, and sometimes a real or embedded database — by loading part or all of the Spring application context.

A healthy test suite favors many fast unit tests for business logic and a smaller number of integration tests for critical end-to-end flows, since integration tests are slower (due to context startup) and more brittle to unrelated changes. Spring Boot supports both: plain JUnit + Mockito for unit tests, and annotations like @SpringBootTest for full-context integration tests.

// Unit test — no Spring context
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
    @Mock private PaymentGateway paymentGateway;
    @InjectMocks private OrderService orderService;
}

// Integration test — loads full Spring context
@SpringBootTest
class OrderIntegrationTest { ... }

यूनिट टेस्टिंग किसी एक क्लास या मेथड को पूरी तरह अलग करके सत्यापित करती है, जिसमें सभी डिपेंडेंसीज़ को Mockito से मॉक किया जाता है, जिससे टेस्ट तेज़ चलता है और कोई स्प्रिंग कॉन्टेक्स्ट लोड नहीं होता। इंटीग्रेशन टेस्टिंग यह सत्यापित करती है कि कई कंपोनेंट्स एक साथ कैसे काम करते हैं — कंट्रोलर, सर्विस, रिपॉज़िटरी — स्प्रिंग एप्लिकेशन कॉन्टेक्स्ट का हिस्सा या पूरा लोड करके।

एक स्वस्थ टेस्ट सूट बिज़नेस लॉजिक के लिए कई तेज़ यूनिट टेस्ट और महत्वपूर्ण एंड-टू-एंड फ्लो के लिए कम संख्या में इंटीग्रेशन टेस्ट को प्राथमिकता देता है, क्योंकि इंटीग्रेशन टेस्ट धीमे होते हैं।

// यूनिट टेस्ट — कोई स्प्रिंग कॉन्टेक्स्ट नहीं
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
    @Mock private PaymentGateway paymentGateway;
    @InjectMocks private OrderService orderService;
}

// इंटीग्रेशन टेस्ट — पूरा स्प्रिंग कॉन्टेक्स्ट लोड करता है
@SpringBootTest
class OrderIntegrationTest { ... }

Was this answer clear?