Integration Testing
@SpringBootTest POORA APPLICATION CONTEXT load karta hai — SAARI beans REAL instances mein (mocked nahi), jaise ACTUAL running application. webEnvironment = RANDOM_PORT se EMBEDDED server bhi start hota hai (random port par), TestRestTemplate se REAL HTTP calls TRIGGER ki ja sakti hain — TRUE end-to-end testing.
Database ke liye, Testcontainers library REAL database (PostgreSQL, MySQL) ko DOCKER CONTAINER mein SPIN UP karta hai, JUST FOR TESTING duration. H2 in-memory database se ZYAADA RELIABLE hai — H2 SQL dialect production database (PostgreSQL) se DIFFERENT ho sakta hai, isliye H2 mein PASS hona GUARANTEE nahi karta production mein bhi kaam karega.
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Testcontainers
class OrderIntegrationTest {
@Container
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:15");
@Autowired
private TestRestTemplate restTemplate;
@DynamicPropertySource
static void configureDb(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", postgres::getJdbcUrl);
}
@Test
void shouldCreateAndFetchOrder() {
ResponseEntity<Order> created = restTemplate.postForEntity(
"/api/orders", new OrderDto(...), Order.class);
assertEquals(HttpStatus.CREATED, created.getStatusCode());
}
}- @SpringBootTest = POORA application context, REAL beans, end-to-end
- Testcontainers = REAL database (Docker) testing ke liye
- Test pyramid: zyaada unit tests, kam integration tests
@SpringBootTest POORA APPLICATION CONTEXT load karta hai — SAARI beans (controllers, services, repositories) REAL instances mein, jaise ACTUAL application. @SpringBootTest(webEnvironment = RANDOM_PORT) EMBEDDED SERVER bhi start karta hai, TRUE end-to-end testing ke liye.
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class OrderIntegrationTest {
@Autowired
private TestRestTemplate restTemplate;
@Test
void shouldCreateOrderEndToEnd() {
ResponseEntity<Order> response = restTemplate.postForEntity(
"/api/orders", new OrderDto(...), Order.class);
assertEquals(HttpStatus.CREATED, response.getStatusCode());
}
}Testcontainers library REAL DATABASE (jaise PostgreSQL) ko DOCKER CONTAINER mein SPIN UP karta hai, JUST FOR TESTING — H2 in-memory database se DIFFERENT hai production database (SQL dialects, features), Testcontainers se tests ACTUAL production database ke against RUN hote hain, MORE RELIABLE results.