DEV Community

Devanshu Biswas
Devanshu Biswas

Posted on

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

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

Top comments (0)