Test each boundary at the cheapest level that still gives confidence. Validation - Unit-test custom validators and Bean Validation constraints with a Validator instance. - With @WebMvcTest and MockMvc, send invalid payloads and assert 400 responses with the expected ProblemDetail field errors: mockMvc.perform(post("/api/payments").contentType(APPLICATION_JSON).content("{\"amount\":-5}")) .andExpect(status().isBadRequest()) .andExpect(jsonPath("$.errors.amount").exists()); Authorization - spring-security-test: .with(jwt().authorities(new SimpleGrantedAuthority("SCOPE_payments.write"))), @WithMockUser, or custom security context factories. - Test anonymous requests (401), missing scope or role (403), another user's or tenant's resource (404 or 403), and the allowed case. Persistence - @DataJpaTest for repository queries and mappings, using Testcontainers with the production database engine (PostgreSQL or MySQL) instead of H2, which behaves differently. - Full @SpringBootTest with Testcontainers (Spring Boot's @ServiceConnection simplifies setup) to verify transactions, migrations (Flyway or Liquibase) and constraints. Assert database state after write requests. - Clean data between tests (transaction rollback, truncation scripts, or a fresh schema per test class). External integrations - WireMock (or MockRestServiceServer for RestTemplate and RestClient) to stub HTTP services, including slow responses, 5xx errors, timeouts and malformed payloads. - Testcontainers for Kafka or RabbitMQ to verify messages are published (and consumed) correctly. - Verify resilience behaviour: retries, circuit breakers, idempotency (no double charge on retry). - Contract tests (Pact or Spring Cloud Contract) to keep stubs aligned with real providers. Full flow example for POST /payments - Valid request: 201, payment row saved, outbox event written, gateway called once. - Gateway timeout: 503 or 202 pending, no duplicate charges, retry scheduled. - Duplicate idempotency key: same response returned, gateway not called again. Practices: Arrange-Act-Assert, readable test data builders, reusing Spring contexts to keep tests fast (avoid unnecessary @MockBean variations, which create new contexts), running everything in CI on every pull request, and a regression test for each production bug.
Ravindra Wadile · · 0 likes