How do you Test Microservices effectively?
Topic: microservices, Testing. Level: Hard.
Answer
Use the **test pyramid** adapted for distribution:
- **Unit**: fast, isolated logic.
- **Integration**: a service with its real DB/broker via **Testcontainers**.
- **Contract tests** (Pact/Spring Cloud Contract): verify provider and consumer agree on the API without full end-to-end runs — catch breaking changes early.
- **Component**: one service in isolation with dependencies stubbed.
- **End-to-end**: a few critical happy paths only (slow, brittle).
Also test resilience (chaos/fault injection) and idempotency. Favor contract + integration over sprawling E2E.
```java
// Integration test with a REAL database via Testcontainers
@Testcontainers @SpringBootTest
class OrderRepoTest {
@Container static PostgreSQLContainer<?> db =
new PostgreSQLContainer<>("postgres:16");
@DynamicPropertySource
static void props(DynamicPropertyRegistry r) {
r.add("spring.datasource.url", db::getJdbcUrl);
}
@Test void savesAndReadsOrder() { /* real SQL, no mocks */ }
}
```