Testing

Prove it works before production does. JUnit 5, Mockito mocks and spies, Spring test slices, MockMvc, Testcontainers, TDD and what coverage really tells you.

Topics in this section

The test pyramid

Picture a pyramid. At the bottom, lots of fast unit tests check single bricks. In the middle, fewer integration tests check the bricks fit together. At the top, a handful of end-to-end tests walk through the finished house.

JUnit 5 essentials

JUnit is the referee. @Test marks each match, @BeforeEach sets up the pitch before every match, and assertions blow the whistle when something's wrong.

Mockito: mocks, spies & verify

A mock is a cardboard stunt double: it looks like the real actor but does nothing unless you script it. A spy is the real actor wearing an earpiece: they do their real job unless you whisper a different line.

@SpringBootTest vs test slices

@SpringBootTest opens the whole restaurant just to taste one dish. Test slices open a single room: @WebMvcTest only the front counter, @DataJpaTest only the storeroom. They're faster, and you know exactly what broke.

Testcontainers

An in-memory H2 database is a cardboard cut-out of Postgres: it looks similar until you lean on it. Testcontainers starts the real Postgres in Docker for your tests, then throws it away.

TDD & code coverage

TDD is writing the exam question before the answer. Red: a failing test. Green: the simplest code that passes. Refactor: tidy up while the test watches your back. Coverage shows which lines ran during tests — not whether anyone checked the result.

Each topic pairs a plain-language explanation with code, interview questions, and related practice where available.