The testing pyramid, unit tests & Mockito
Unit vs slice vs integration vs end-to-end tests, writing fast unit tests with JUnit 5 and Mockito, what to mock (and what not to), fixtures and naming.
The pyramid
/\ E2E (browser/API against a deployed stack) few, slow, brittle
/ \
/----\ Integration (Spring context + real Postgres) some, slower, high confidence
/ \
/--------\ Slice (@WebMvcTest, @DataJpaTest) focused
/ \
/------------\ Unit (plain Java + mocks) many, milliseconds
Some teams prefer a testing trophy, which puts more weight on integration tests. With Testcontainers making real-DB tests cheap, both RM and IR3D lean that way.
Unit tests with JUnit 5 + Mockito
@ExtendWith(MockitoExtension.class)
class BookingServiceTest {
@Mock BookingRepository bookings;
@Mock RoomRepository rooms;
@Mock NotificationService notifications;
@InjectMocks BookingService service;
@Test
@DisplayName("approve fails with 409 when the room is full")
void approveFullRoom() {
Room room = TestFixtures.room(capacity(2), occupancy(2));
Booking b = TestFixtures.pendingBooking(room);
when(bookings.findById(b.getId())).thenReturn(Optional.of(b));
when(rooms.findByIdForUpdate(room.getId())).thenReturn(Optional.of(room));
assertThatThrownBy(() -> service.approveBooking(b.getId(), manager()))
.isInstanceOf(RoomFullyOccupiedException.class);
verify(notifications, never()).bookingApproved(any()); // no side effect
}
}
The structure is Arrange, Act, Assert (or Given/When/Then), with one behaviour per test.
In your projects
src/test/... AuthServiceTest · BookingServiceTest · RoomServiceTest · WaitlistServiceTest · BookingExpiredSweeperTest · JwtServiceTest · JwtAuthenticationFilterTest · testsupport/TestFixtures · TESTING.mdA solid unit layer: services, the sweeper, JWT creation and parsing, and the filter. TestFixtures builds valid domain objects, src/test/data/rooms.json holds data, and TESTING.md documents the conventions.
IerReportStrategyTest · ResilientPublisherTestStrategies are pure logic, which makes them ideal unit-test targets. ResilientPublisherTest simulates AmqpException to prove the fallback works.
StoreApplicationTests.contextLoads() · entities/CartTest.javaStore used to have only a context-load test, and the cart bug from the idempotency lesson went unnoticed. Store PR #1 added CartTest, a plain unit test with no mocks, which fails on the old code and passes on the fix. That’s the ideal regression test. Rich domain entities (Cart, Order) are the easiest code to unit test.
What to mock
| Mock | Don’t mock |
|---|---|
| External systems (Stripe, SMTP, Paystack) behind ports | Value objects, entities, DTOs |
| Slow collaborators in a unit test | Your database in an integration test (use the real one) |
Clocks (Clock.fixed(...)) |
The class under test |
| Types you don’t own (mock your adapter instead) |
Over-mocking gives tests that pass while production breaks, because you’ve only tested your assumptions about the mocks.
Related concepts you must know
- AssertJ for fluent assertions (
assertThat(x).isEqualTo(...)). - Parameterized tests (
@ParameterizedTest @CsvSource) for validators and state transitions. - Test naming:
methodName_condition_expectedResult, or a@DisplayNamesentence. - Mutation testing (PIT) checks whether tests actually catch bugs.
- TDD: write a failing test, then make it pass, then refactor.