Testing in Spring Boot series: 1. Unit testing with JUnit and Mockito · 2. Slice tests and Testcontainers
A good unit test catches a business-logic bug in milliseconds and lets you refactor without fear; a bad one just mirrors the code and breaks every time the implementation changes. This post shows how to pick what is worth testing, write it with JUnit 5/6 and Mockito, and review a test suite an AI generated. The running example is the real UserServiceTest from a Spring Boot 4 lab (6 tests, all passing).
At a glance:
flowchart TD
A{"What is the code?"} -->|"Decisions"| B["Unit test"]
A -->|"Wiring"| C["Slice or integration test"]
B --> D["Arrange, Act, Assert"]
D --> E["Stub supplies data"]
D --> F["Verify side effects"]
E --> G{"Delete logic, test red?"}
F --> G
G -->|"No"| H["Useless test"]
G -->|"Yes"| I["Measure with mutation testing"]
1. Why developers write their own tests
Key idea: automated tests are a safety net for change: every edit reruns hundreds of scenarios in seconds. Their value grows with how often the code changes, not with how many test lines you have.
- Regression: fixing bug A breaks feature B. An old test goes red on your machine, before QA ever sees it.
- Safe refactoring: change the internal structure while behaviour stays the same; tests written against behaviour stay green.
- Living documentation: a name like
rejectsDuplicateEmailWithoutHashingOrSavingstates a business rule more precisely than a wiki page. - Bug fixes start with a test: write a test that reproduces the bug (red), fix it (green), and that bug can’t come back.
Not worth unit-testing: getters/setters, code that only forwards a call, a prototype you’ll throw away. Manual and exploratory testing still matter for UX; automation is for what repeats.
2. The test pyramid and its critics
Key idea: the pyramid (many unit, fewer integration, very few E2E) is a cost principle, not a mandatory ratio. In a REST service that is mostly CRUD, most of the risk sits where you touch the DB and HTTP, so integration tests take a bigger share.
| Kind | Runs in | Catches | Cost |
|---|---|---|---|
| Unit | ms, no Spring, no DB | logic errors, branches, normalisation | cheap, easy to debug |
| Slice / integration | 100s of ms – seconds | JSON mapping, validation, queries, transactions, security | medium |
| E2E | seconds – minutes | end-to-end flow with real UI/infrastructure | expensive, often flaky |
The 70/20/10 split in the course material is a template for logic-heavy systems. Two common critiques:
- Testing trophy (Kent C. Dodds): the centre of gravity is integration, because it buys the most confidence per hour of writing.
- Testing honeycomb (Spotify, for microservices): few isolated unit tests, many tests at the service boundary with a real DB.
A practical rule: complex logic gets thorough unit tests; “load from DB, map, return JSON” gets slice/integration tests (part 2).
3. What to test at unit level
Key idea: a unit test pays off when the method makes a decision: a branch, a calculation, a normalisation, a required ordering. The check: “if I delete this logic, does a test go red?”
The course says “a service with no logic makes unit tests pointless” and uses findById(id).orElseThrow(...) as the example. That example actually has a branch (found / not found); it is just trivial and sits right on the wiring. A clearer rule:
- Unit-test: business rules (reject a duplicate email), data transformation (normalise email, hash password), meaningful ordering (check for duplicates before hashing), calculations (price, tax, expiry date).
- Don’t unit-test: a method that calls the repository and returns; annotation mapping; JPQL queries. Mocking the repository there only checks that the code calls… what it calls.
4. Shape of a test: AAA and naming
Key idea: each test has three blocks: Arrange (set up), Act (call exactly one behaviour), Assert (check the result); BDD calls them Given–When–Then. The name states the behaviour and the outcome, not the method name.
@Test
void rejectsDuplicateEmailWithoutHashingOrSaving() {
// Arrange (Given): the email already exists
when(users.existsByEmailIgnoreCase("an@example.dev")).thenReturn(true);
// Act + Assert (When/Then): rejected, not hashed, not saved
assertThatThrownBy(() -> service.create(req))
.isInstanceOf(DuplicateResourceException.class)
.hasMessageContaining("an@example.dev");
verify(users, never()).save(any());
verifyNoInteractions(encoder);
}
- One test, one reason to fail. Several asserts are fine as long as they describe one behaviour.
- No
ifor loops inside a test; for many inputs use a parameterized test. - Name it
does_X_when_Yor as an English sentence; use@DisplayNamewhen you want another language in the report.
5. JUnit 5/6: the everyday parts
Key idea: JUnit Jupiter gives you @Test, lifecycle with @BeforeEach, grouping with @Nested, and many inputs with @ParameterizedTest; prefer AssertJ for readable assertions. Spring Boot 4 brings JUnit 6, but the Jupiter API is unchanged, so JUnit 5 code runs as is.
| Feature | Use it for |
|---|---|
@BeforeEach / @AfterEach |
rebuild the fixture per test (JUnit creates a new instance per test) |
@BeforeAll (static) |
expensive shared setup: a container, a big file |
@Nested + @DisplayName |
group tests by method or by situation |
@ParameterizedTest + @ValueSource / @CsvSource / @MethodSource |
one rule, many inputs |
assertThrows / assertThatThrownBy |
check the exception and its message |
@Disabled, @Tag("slow") |
switch off with a reason, select groups to run |
@ParameterizedTest
@ValueSource(strings = {"AN@EXAMPLE.DEV", " an@example.dev ", "An@Example.Dev"})
void normalizesEmailVariants(String email) {
when(users.existsByEmailIgnoreCase("an@example.dev")).thenReturn(true);
var r = new CreateUserRequest("An", email, "plain-pass-1", null);
assertThatThrownBy(() -> service.create(r)).isInstanceOf(DuplicateResourceException.class);
}
The stub only matches "an@example.dev". If the service forgets trim() or toLowerCase, the stub returns the default false and the test goes red: this test really checks the normalisation.
JUnit 6 in Spring Boot 4, AssertJ and some less-used features
- JUnit 6 (shipped with Spring Boot 4): requires Java 17+, aligns the Platform/Jupiter/Vintage modules on one version number, uses JSpecify for nullness. Jupiter annotations and
Assertionskeep their names. Things to watch when upgrading: JUnit 4 tests need the separate Vintage engine (Boot hasn’t bundled it since 2.4, and JUnit 6 deprecates it), and old third-party extensions may need new versions. - AssertJ comes with
spring-boot-starter-test:assertThat(list).extracting(User::getEmail).containsExactly(...),assertThat(opt).isPresent(), clearer failure messages thanassertEquals. @TestInstance(Lifecycle.PER_CLASS): one instance for the whole class, allows non-static@BeforeAll, but state leaks between tests.@RepeatedTest(100)to hunt flaky tests;@Timeoutto stop a hanging test.assertAll(...)runs every assertion and reports all failures instead of stopping at the first.
6. Mockito: mocks, stubs, spies, fakes
Key idea: a test double stands in for a dependency. A stub returns canned data, a mock records calls so you can verify them, a spy wraps a real object, a fake is a real but simplified implementation (a repository backed by a HashMap). Mockito creates mocks, stubs and spies; fakes you write yourself.
| Kind | Purpose | Mockito |
|---|---|---|
| Stub | provide indirect input | when(repo.exists(..)).thenReturn(true) |
| Mock | check indirect output (side effects) | verify(repo).save(..), never() |
| Spy | real object, override a few methods | spy(realObject), doReturn(..).when(spy).m() |
| Fake | simple but working logic | hand-written InMemoryUserRepository |
The tools the lab uses most:
thenAnswer(inv -> inv.getArgument(0)):savereturns the entity it was given, like JPA does.verify(x, never()),verifyNoInteractions(encoder): check what must not happen (failing early means no hashing, no saving).InOrder: ordering that matters to the business (check duplicate → hash → save).ArgumentCaptorto grab the object that was passed and assert several fields;argThat(...)for a short condition right insideverify.
ArgumentCaptor<User> saved = ArgumentCaptor.forClass(User.class);
verify(users).save(saved.capture());
assertThat(saved.getValue().getPassword()).isEqualTo("{bcrypt}hash");
assertThat(saved.getValue().getEmail()).isEqualTo("an@example.dev");
What not to mock, and injecting a Clock to test time
Don’t mock:
- Value objects, DTOs, records, entities: build real ones with constructors. Mocking
Userto stubgetEmail()makes the test long and brittle. - Types you don’t own (
RestTemplate,JdbcTemplate, third-party SDKs): mocking them only checks that you call the API the way you think it works. Wrap it behind an interface of your own (an adapter) and mock that; test the adapter with an integration test (WireMock, Testcontainers). - The class under test: if you need to spy on it to stub an internal method, the class does too much.
- Statics and
final: Mockito 5 can mock them (inline mock maker), but needing to is a sign the design is hard to test.
Time: code that calls Instant.now() directly can’t test “the token expires after 7 days”. The lab injects a Clock:
@Bean Clock clock() { return Clock.systemUTC(); } // production
// in a test
Clock fixed = Clock.fixed(Instant.parse("2026-01-01T00:00:00Z"), ZoneOffset.UTC);
var service = new RefreshTokenService(tokens, props, fixed);
// expired? use Clock.offset(fixed, Duration.ofDays(8))
Same for UUID/SecureRandom: inject a supplier if the test needs a fixed value.
7. Lab: UserServiceTest
Key idea: UserService.create makes three decisions: normalise the email, reject a duplicate before paying for a BCrypt hash, and store only the hashed password. Six tests, each catching one specific wrong implementation.
Code under test (Spring Boot 4.0.3, Java 21):
@Transactional
public UserResponse create(CreateUserRequest req) {
String email = req.email().trim().toLowerCase(Locale.ROOT);
if (users.existsByEmailIgnoreCase(email)) {
throw new DuplicateResourceException("User", "email", email);
}
User saved = users.save(new User(req.name().trim(), email, passwordEncoder.encode(req.password()), req.gender()));
return UserResponse.from(saved);
}
| Test | Wrong implementation it catches |
|---|---|
savesNormalizedEmailAndEncodedPassword |
stores the raw password, forgets to normalise email/name |
checksDuplicateBeforeSaving (InOrder) |
hashes before checking (pays ~100 ms of BCrypt for a rejected request) |
rejectsDuplicateEmailWithoutHashingOrSaving |
still saves on duplicate, still calls the encoder |
normalizesEmailVariants ×3 |
duplicate check sensitive to case or whitespace |
Running mvn test: these 6 tests pass in about 0.25 s without starting Spring. The test uses @Mock for UserRepository and PasswordEncoder and @InjectMocks UserService. Constructor injection keeps this simple: no Spring, no reflection (IoC and DI).
The full UserServiceTest
@ExtendWith(MockitoExtension.class) // strict stubs: an unused when(...) fails the test
class UserServiceTest {
@Mock UserRepository users;
@Mock PasswordEncoder encoder;
@InjectMocks UserService service;
CreateUserRequest req = new CreateUserRequest(" An ", "An@Example.dev", "plain-pass-1", User.Gender.FEMALE);
@Nested
@DisplayName("create()")
class Create {
@Test
void savesNormalizedEmailAndEncodedPassword() {
when(users.existsByEmailIgnoreCase("an@example.dev")).thenReturn(false);
when(encoder.encode("plain-pass-1")).thenReturn("{bcrypt}hash");
when(users.save(any(User.class))).thenAnswer(inv -> inv.getArgument(0));
var result = service.create(req);
ArgumentCaptor<User> saved = ArgumentCaptor.forClass(User.class);
verify(users).save(saved.capture());
assertThat(saved.getValue().getPassword()).isEqualTo("{bcrypt}hash");
assertThat(saved.getValue().getEmail()).isEqualTo("an@example.dev");
assertThat(result.name()).isEqualTo("An");
}
@Test
void checksDuplicateBeforeSaving() {
when(users.existsByEmailIgnoreCase(any())).thenReturn(false);
when(encoder.encode(any())).thenReturn("h");
when(users.save(any())).thenAnswer(inv -> inv.getArgument(0));
service.create(req);
InOrder order = inOrder(users, encoder);
order.verify(users).existsByEmailIgnoreCase("an@example.dev");
order.verify(encoder).encode("plain-pass-1");
order.verify(users).save(argThat(u -> !u.getPassword().equals("plain-pass-1")));
}
@Test
void rejectsDuplicateEmailWithoutHashingOrSaving() {
when(users.existsByEmailIgnoreCase("an@example.dev")).thenReturn(true);
assertThatThrownBy(() -> service.create(req))
.isInstanceOf(DuplicateResourceException.class)
.hasMessageContaining("an@example.dev");
verify(users, never()).save(any());
verifyNoInteractions(encoder); // BCrypt is slow: do not pay for it on a rejected request
}
@ParameterizedTest
@ValueSource(strings = {"AN@EXAMPLE.DEV", " an@example.dev ", "An@Example.Dev"})
void normalizesEmailVariants(String email) {
when(users.existsByEmailIgnoreCase("an@example.dev")).thenReturn(true);
var r = new CreateUserRequest("An", email, "plain-pass-1", null);
assertThatThrownBy(() -> service.create(r)).isInstanceOf(DuplicateResourceException.class);
}
}
}
Note: the @Nested class is non-static, so it can use the outer users and req fields. Surefire reports these under the group name create() (6 tests, 0 failures).
8. Reviewing AI-written tests, coverage and mutation testing
Key idea: AI writes tests fast and syntactically right, but often produces mirror tests, covers only the happy path and over-verifies. Review with “does it go red if I delete the logic?”, and measure test strength with mutation testing rather than coverage %.
Checklist for reviewing a unit-test suite:
- Which one line of logic, when deleted or flipped, turns each test red? If you can’t name it, the test is useless.
- Mocks in the right place: only dependencies, never the class under test, never records/DTOs.
- Error branches and early returns have
never()/verifyNoInteractions? - Transformed data (hashing, normalisation) checked with a captor or
argThat? - Edge cases: null, empty, whitespace, letter case, boundaries (0, max), time (use a
Clock). - Independence: green when run alone or in another order; no dependence on the machine’s clock, time zone or locale.
Mutation testing with PIT
Mutation testing changes your code slightly (flips > to >=, removes a method call, returns null); each change is a mutant, and the tests run again. A red test “kills” the mutant; if the tests stay green the mutant “survives”, meaning a behaviour change went unnoticed.
<plugin>
<groupId>org.pitest</groupId>
<artifactId>pitest-maven</artifactId>
<!-- add pitest-junit5-plugin as a plugin dependency -->
<configuration>
<targetClasses><param>dev.lab.hr.user.*</param></targetClasses>
</configuration>
</plugin>
mvn org.pitest:pitest-maven:mutationCoverage produces an HTML report. Example with UserService.create: without normalizesEmailVariants, the mutant “drop toLowerCase” would survive while line coverage stays at 100%. PIT is slow (it reruns tests many times), so run it on packages with important logic or nightly, not on every commit. I haven’t run PIT on this lab; the mutant example above is reasoned from how the tests are written.
Exercises
- Write unit tests for
RefreshTokenService.rotatein the lab using Mockito and a fixedClock: (a) a valid token is revoked and a new token in the same family is saved; (b) reusing a revoked token revokes the whole family and throwsInvalidRefreshTokenException; (c) a token expiring exactly atexpiresAtis rejected. - For each of your tests, write down which line of code, if deleted, turns it red.
Solution to exercise 1 (sketch)
@ExtendWith(MockitoExtension.class)
class RefreshTokenServiceTest {
@Mock RefreshTokenRepository tokens;
Clock clock = Clock.fixed(Instant.parse("2026-01-01T00:00:00Z"), ZoneOffset.UTC);
JwtProperties props = new JwtProperties("c2VjcmV0LXNlY3JldC1zZWNyZXQtc2VjcmV0LTMyYnl0ZXMh",
"test", Duration.ofMinutes(15), Duration.ofDays(7));
RefreshTokenService service;
User user = new User("A", "a@x.dev", "h", User.Gender.OTHER);
@BeforeEach void setUp() { service = new RefreshTokenService(tokens, props, clock); }
@Test
void reuseOfRevokedTokenRevokesFamily() {
var old = new RefreshToken("hash", "fam-1", user, clock.instant().plusSeconds(60));
old.revoke(clock.instant());
when(tokens.findByTokenHash(RefreshTokenService.sha256("raw"))).thenReturn(Optional.of(old));
assertThatThrownBy(() -> service.rotate("raw")).hasMessageContaining("reuse");
verify(tokens).revokeFamily("fam-1", clock.instant());
verify(tokens, never()).save(any());
}
@Test
void tokenExpiringExactlyNowIsRejected() {
var t = new RefreshToken("hash", "fam-1", user, clock.instant()); // expiresAt == now
when(tokens.findByTokenHash(any())).thenReturn(Optional.of(t));
assertThatThrownBy(() -> service.rotate("raw")).hasMessageContaining("expired");
}
}
The test lives in package dev.lab.hr.auth because RefreshToken’s constructor is package-private. Test (b) goes red if revokeFamily is removed; test (c) goes red if !isAfter(now) becomes isBefore(now). This solution follows the lab code but was not run; the real flow is covered by the integration test in part 2.
Remember
- Explain why the test pyramid is a cost principle and when integration tests should take the biggest share.
- Tell decisions (unit test) from wiring (slice/integration test) inside a service.
- Tell stubs, mocks, spies and fakes apart, and pick
verify,never,InOrderor a captor correctly. - Know why strict stubs fail on unused stubs, and why you don’t mock value objects or third-party libraries.
- Answer “we have 90% coverage, are our tests good?” with mutation testing.
Interview questions
Junior
What is the difference between a mock and a stub?
A stub feeds data into the code under test; a mock is used to check what the code called (side effects).
In Mockito the same object can play both roles: when(repo.exists(..)).thenReturn(true) is a stub, verify(repo).save(..) uses it as a mock. Rule of thumb: stub queries, verify commands; don’t verify calls that only fetch data.
What is AAA?
Arrange – Act – Assert: set up data and dependencies, call exactly one behaviour, then check the result.
Separating the three blocks makes a test read like a scenario and keeps “one test, one behaviour”. BDD calls the same idea Given – When – Then.
Mid
When should you unit-test a service method, and when not?
Unit-test it when it makes decisions (branches, calculations, normalisation, ordering); not when it only forwards calls to the repository.
For pure wiring, mocking the repository just restates the implementation and breaks on refactoring. Cover that with @DataJpaTest or an integration test against a real DB. The check: does a test go red if I delete this logic?
When do you use an ArgumentCaptor?
When you need to check the object passed to a dependency, especially one the code builds internally (an entity whose password is hashed before saving).
The captor grabs the real argument so you can assert each field with clear messages. argThat is shorter for a single condition, especially inside InOrder.
Why does Mockito throw UnnecessaryStubbingException, and how do you handle it?
Because MockitoExtension runs strict stubs and a when(...) was never used by the code. Usually delete the stub rather than turning the check off.
An unused stub hints at a copy-pasted test or a branch that changed. Use lenient() only for shared stubs in @BeforeEach that are deliberately optional.
How do you test code that depends on the current time?
Inject a java.time.Clock instead of calling Instant.now() directly; tests pass Clock.fixed or Clock.offset.
That lets you check boundaries like “expires exactly now” without Thread.sleep and without depending on the CI machine’s time zone.
Senior
The team has 85% coverage but bugs still slip through. How do you assess the test suite?
Coverage only says code ran, not that it was checked. I’d run mutation testing (PIT) on the packages with important logic and read the surviving mutants.
- Look for tests without asserts, mirror tests, happy-path-only tests.
- Check where the escaped bugs live: logic (missing unit tests) or wiring (missing integration tests against real DB/HTTP).
- Change the goal from coverage % to: every bug fix comes with a reproducing test, and critical logic keeps a stable mutation score.
Would you mock RestTemplate or a payment SDK in a unit test?
No, I don’t mock types I don’t own. I wrap them behind my own interface (an adapter), mock that interface in unit tests, and test the adapter with an integration test using WireMock or a sandbox.
Mocking the library only checks that the code calls the API the way I assume it behaves; when the library changes behaviour (timeouts, error codes) the test stays green while production breaks.
Useful phrases for interviews
- “I unit-test decisions and integration-test the wiring.”
- “Every bug fix starts with a failing test, so the regression can’t come back.”
- “I stub queries and verify commands.”
- “If a test doesn’t go red when I delete the logic, it isn’t testing anything.”
- “Strict stubs fail the test when a stubbing is never used, which keeps tests honest.”
- “I inject a Clock so tests can control time instead of sleeping.”
- “Don’t mock what you don’t own; wrap it in an adapter and integration-test the adapter.”
- “Coverage tells you what ran; mutation testing tells you what your tests would notice.”
- “The test pyramid is about cost, not a fixed ratio.”
- “A mock can’t show you a check-then-act race; only the unique constraint and a real database can.”
Notes based on Hỏi Dân IT course material, rewritten and extended in my own words.