OrderHub Day 8: Testing With JUnit 5, Mockito & MockMvc (Spring Boot)

java dev.to

OrderHub Day 8: tests. The feature that lets you change everything else without fear. Today the backend gets a real test suite — domain unit tests, Mockito service tests, and MockMvc web-slice tests. 16 green.

🧪 See the suite run (+ break it): https://dev48v.infy.uk/orderhub/day8-testing.html

The testing pyramid, in practice

Three levels, each isolating something different:

  1. Domain unit test (JUnit 5, no Spring) — pure logic. Order.confirm() moves PLACED → CONFIRMED; confirming twice throws IllegalStateException.
  2. Service test (Mockito) — @Mock the repository so you test the service alone. Stub when(repo.findById(...)), assert it throws OrderNotFoundException on a missing id, verify(repo).save(...) on a place.
  3. Web slice test (@WebMvcTest + MockMvc, @MockBean OrderService) — test the controller without a server or DB: POST valid → 201, blank field → 400 (ProblemDetail), missing id → 404, bad state → 409.

Why slices beat spinning up everything

@WebMvcTest loads only the web layer — fast, focused. Mockito fakes collaborators so a failure points at exactly one class. You get a precise, sub-second feedback loop.

The payoff

Flip a bug into confirm() and two tests go red with Expected CONFIRMED / Got PLACED. That's the whole point — the suite catches the regression before your users do, so refactors stay safe.

🔨 Full walkthrough (JUnit 5 → Mockito → MockMvc + jsonPath) on the page: https://dev48v.infy.uk/orderhub/day8-testing.html

OrderHub — a production-grade Spring Boot backend, one feature a day.
🌐 https://dev48v.infy.uk · Code: https://github.com/dev48v/order-hub-from-zero

Source: dev.to

arrow_back Back to Tutorials