intermediate~3h
Testing Spring Security and Event-Driven Code
How to verify authentication and authorization behavior on REST endpoints without a real identity provider, and how to test Kafka-based producers and consumers at both the unit and integration level, including the asynchronous-polling discipline that keeps those tests fast and non-flaky.
Learning objectives
- Simulate authenticated and anonymous identities in MockMvc tests with @WithMockUser and @WithAnonymousUser
- Distinguish the three HTTP status tiers a security test suite must cover: 401, 403, and 200/201
- Test method-level authorization enforced by @PreAuthorize independently of the web layer
- Avoid the CSRF-related 403 that silently breaks POST/PUT tests in MockMvc
- Unit test Kafka message producers with Mockito and integration test @KafkaListener consumers against a real broker
- Replace Thread.sleep in asynchronous tests with Awaitility's condition polling
This is a Pro chapter
Sign in, then upgrade to Pro or Power to unlock this and the full Core Java Mastery library.
Testing Spring Security and Event-Driven Code