Q34 of 38 · Manual & exploratory
How would you set up a test strategy for a brand-new microservice?
Short answer
Short answer: Cover unit (logic), contract (API surface), integration (database/dependencies), and a tiny set of E2E for critical flows. Start with consumer-driven contracts so the service can deploy independently. Avoid heavy E2E from day one.
Detail
A new microservice is a clean slate to design test strategy properly. The "trophy" or "diamond" shape suits it better than a classic pyramid: heavy on contract and integration tests, lighter on unit (microservices typically have less internal logic than monoliths), and minimal E2E (E2E across services is brittle and slow).
Layer 1 — Unit tests: for the genuine business logic the service owns. Pure functions, validation, calculation. Fast (<1s total), fully isolated. If the service is mostly thin orchestration, this layer will be small, and that's fine.
Layer 2 — Integration tests: verifying the service works correctly with its real dependencies (the actual database via testcontainers, the actual cache, an actual message broker). These are the highest-value tests because they catch the real-world failures (transaction handling, schema migration, concurrency).
Layer 3 — Contract tests: both inbound (this service's API contract) and outbound (the contracts of services this one calls). Tools like Pact let consumer teams record their expectations of your service; your CI verifies the recorded expectations every build. This is what lets services deploy independently — break the contract, fail consumer's CI, fix before merge.
Layer 4 — A small E2E set: 3–10 critical user-facing flows, run nightly or pre-deploy, not on every PR. E2E across multiple services is brittle and slow; treat it as a smoke check, not a primary safety net.
Cross-cutting from day one: schema-first APIs (OpenAPI/JSON Schema) as the single source of truth for contract tests, validators, and client SDKs; an explicit test-data management strategy (per-test transaction rollback? throwaway schema?); observability built-in (canary, feature flags, high-resolution monitoring); a local dev environment (docker-compose) so devs can run tests offline.
The pitfall: building a full E2E suite first — slow, brittle, won't deploy independently. Or skipping contract tests entirely — without them, microservices coordination is a nightmare.