ENGINEERING NOTES / JAVA
Testing service and controller layers in Spring Boot
Using JUnit, Mockito, and MockMvc to write meaningful tests for Spring Boot applications without an overloaded test context.
MANOHAR · 6 MIN READ · Java · Spring Boot · Testing · 2026-11
KEY ARCHITECTURAL TAKEAWAYS
- 01.Avoid annotating every test with @SpringBootTest; it starts the entire application context and slows test suites to a crawl.
- 02.Use @WebMvcTest for controller validation and HTTP contract tests; use pure Mockito unit tests for service business rules.
- 03.Automated testing of centralized @ControllerAdvice ensures error payloads conform strictly to RFC 7807 specifications.
01 / The Performance Trap of @SpringBootTest
In many beginner Spring Boot codebases, developers slap @SpringBootTest on every test class. While this verifies the full Spring wiring, it means Hibernate connects to the database, Flyway runs migrations, and every bean is instantiated for even simple unit checks. As the application grows, test suites take minutes instead of seconds to run.
In IncidentHub, testing was split into two focused, high-speed layers: pure Mockito unit tests for service-layer lifecycle rules, and targeted @WebMvcTest slice tests for HTTP endpoints.
02 / Verifying State Transitions with Mockito
Service tests should run in milliseconds without any Spring context overhead. By using MockitoExtension and @Mock annotations on the repository, we can verify that illegal status transitions are rejected before touching persistence.
03 / Testing HTTP Error Contracts with MockMvc
Using @WebMvcTest(IncidentController.class) loads only the web layer (Fast and lightweight). We test that @Valid triggers 400 Bad Request on invalid payloads, and that our @ControllerAdvice exception handler catches custom business exceptions to produce standardized JSON error responses.