Sub topic 3
Unit testing services with JUnit 5, Mockito, and AssertJ
This chapter assumes you can write a basic JUnit test, you know what a Spring bean and constructor injection are, and you have a Gradle or Maven project with spring-boot-starter-test on the test classpath. The aim is to test a service class in isolation, without starting Spring, so the test runs in milliseconds.
Why a service test needs no Spring context
A service class holds business logic. It usually depends on other beans, such as a repository. Spring wires those dependencies at runtime, but the logic itself is plain Java. If you call new GreetingService(repository) yourself and pass in a fake repository, the service behaves exactly as it does in production.
Starting a Spring context to test this logic adds seconds of startup time and pulls in configuration that has nothing to do with the rule you are checking. A plain unit test avoids both costs. It also fails for one reason only: the service code is wrong.
Three libraries do the work:
| Library | Role in the test |
|---|---|
| JUnit 5 (Jupiter) | Discovers and runs tests, provides lifecycle annotations and the extension model |
| Mockito | Creates fake collaborators and records how they were called |
| AssertJ | Fluent assertions that read like sentences and give detailed failure messages |
All three arrive with spring-boot-starter-test. In Gradle, useJUnitPlatform() tells the build to run JUnit 5 tests:
dependencies {
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('test') {
useJUnitPlatform()
}The class under test
The examples use a small service that looks up a stored greeting by name. The repository and the entity are shown here so that every example in this chapter is complete.
public record Greeting(String name, String text) {
}import java.util.Optional;
public interface GreetingRepository {
Optional<Greeting> findByName(String name);
}import java.util.Optional;
import org.springframework.stereotype.Service;
@Service
public class GreetingService {
private final GreetingRepository repository;
public GreetingService(GreetingRepository repository) {
this.repository = repository;
}
public String greetingFor(String name) {
return repository.findByName(name)
.map(Greeting::text)
.orElse("Hello, stranger");
}
}Constructor injection matters here. The service declares its dependency in its constructor, so a test can supply any implementation without reflection or a container. Field injection with @Autowired on a private field makes the same test harder to write.
A first test with Mockito and AssertJ
A Mockito mock is an object that implements the same type as the real collaborator but does nothing until you tell it what to return. You use when(...).thenReturn(...) to define that behavior, which is called stubbing.
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
class GreetingServiceTest {
@Mock
GreetingRepository repository;
@InjectMocks
GreetingService service;
@Test
void returnsStoredGreeting() {
when(repository.findByName("Ada"))
.thenReturn(Optional.of(new Greeting("Ada", "Hello, Ada")));
assertThat(service.greetingFor("Ada")).isEqualTo("Hello, Ada");
}
}Each annotation has a specific job:
@ExtendWith(MockitoExtension.class)is a JUnit 5 extension. Before each test it creates the mocks and injects them. It is not a Spring annotation, and no Spring context starts.@Mockcreates a mock ofGreetingRepository.@InjectMocksbuildsGreetingServiceand passes the mocks to its constructor.assertThat(...)comes from AssertJ. The call starts a chain of assertions on the value you pass in.
The test follows the arrange, act, assert pattern. The stubbing arranges the world, the call to greetingFor acts, and assertThat checks the result. Keeping those three parts visibly separate makes tests easy to read.
Testing the other branch
One test covers only one path. The service has a fallback for a missing name, and that path needs its own test. Add this method to the same class:
@Test
void returnsDefaultGreetingWhenNameIsUnknown() {
when(repository.findByName("Nobody")).thenReturn(Optional.empty());
assertThat(service.greetingFor("Nobody")).isEqualTo("Hello, stranger");
}Name each test after the behavior it checks. A failing test called returnsDefaultGreetingWhenNameIsUnknown tells you what broke before you open the file.
Strict stubs: Mockito's safety net
MockitoExtension runs in strict stubs mode. If a test stubs a call that the code under test never makes, Mockito fails the test with an UnnecessaryStubbingException. This catches stale setup, such as a stub left behind after a refactor.
Suppose the service changed to look up by lowercase name, but the test still stubs "Ada". The stub is never used, and the service call returns the default text. Two things go wrong at once, and strict stubs makes the cause visible instead of leaving you with a confusing assertion failure only.
If a stub is only needed by some tests in the class, define it inside those tests. Moving everything to @BeforeEach invites the unnecessary-stubbing error in tests that do not use it. As a last resort you can mark a single stub with lenient(), but treat that as a signal to restructure the test.
Verifying interactions
Most assertions should check results. Sometimes the observable result is a call to a collaborator, for example saving an entity or sending a message. Mockito's verify checks that call happened.
Consider a service method that saves a greeting:
public void register(String name) {
repository.save(new Greeting(name, "Hello, " + name));
}For this to compile, add Greeting save(Greeting greeting); to GreetingRepository. The test then checks what was passed to save:
import static org.mockito.Mockito.verify;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
@Captor
ArgumentCaptor<Greeting> captor;
@Test
void registerSavesGreetingForName() {
service.register("Grace");
verify(repository).save(captor.capture());
assertThat(captor.getValue())
.extracting(Greeting::name, Greeting::text)
.containsExactly("Grace", "Hello, Grace");
}ArgumentCaptor records the argument so you can assert on its fields. Use verify for side effects that return nothing. Do not verify calls that you have already stubbed and whose result you assert, because that repeats the assertion and ties the test to the implementation.
Testing failures
A service often throws when input is invalid. AssertJ expresses this with assertThatThrownBy or assertThatExceptionOfType. Assume greetingFor rejects blank names:
public String greetingFor(String name) {
if (name == null || name.isBlank()) {
throw new IllegalArgumentException("name must not be blank");
}
return repository.findByName(name)
.map(Greeting::text)
.orElse("Hello, stranger");
}The test then reads:
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.verifyNoInteractions;
@Test
void rejectsBlankName() {
assertThatThrownBy(() -> service.greetingFor(" "))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("name must not be blank");
verifyNoInteractions(repository);
}The verifyNoInteractions call confirms that validation happens before any database access. Here the interaction check is the point of the test, so it belongs.
Many inputs, one test
JUnit 5 parameterized tests run one method against a table of inputs. They need the junit-jupiter-params module, which the starter includes through junit-jupiter.
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
@ParameterizedTest
@ValueSource(strings = {"", " ", " "})
void rejectsEveryBlankName(String name) {
assertThatThrownBy(() -> service.greetingFor(name))
.isInstanceOf(IllegalArgumentException.class);
}Each value appears as its own entry in the test report, so a failure names the input that caused it.
The service test lifecycle
The diagram shows what happens for each test method. A fresh service and fresh mocks are created every time, so tests cannot leak state into each other.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `NullPointerException` on the service or repository | Missing `@ExtendWith(MockitoExtension.class)`, so the mocks were never created | Add the extension to the test class |
| `UnnecessaryStubbingException` | A stub that the test never triggers | Remove the stub, or correct the argument it expects |
| Mock returns `null` or an empty value | The call was made with arguments different from the stubbed ones | Check the argument values, or use a matcher such as `any()` |
| `InvalidUseOfMatchersException` | Matchers mixed with raw values in one call | Use matchers for every argument, for example `eq("Ada")` |
| Test passes but checks nothing | Assertion written without a terminal check, such as `assertThat(x)` alone | End the chain with a method such as `isEqualTo` |
Note the last row. assertThat(value) alone does not assert anything. The check happens only when you call a method on the result.
When a unit test is the wrong tool
A unit test with a mocked repository proves that the service logic is right given the repository's stated behavior. It cannot prove that a derived query such as findByName produces correct SQL, that a transaction rolls back, or that a controller maps a URL correctly. Later chapters cover those cases with slice tests and real infrastructure. Use unit tests for branching logic, calculations, validation, and the orchestration of collaborators.
Exercise
A service method register(String name) calls repository.findByName(name) and, only if the result is empty, calls repository.save(...). Describe two unit tests that cover this method, and say which Mockito feature each one needs.
Show answer
First test: stub findByName to return Optional.empty(), call register, and use verify(repository).save(...), with an ArgumentCaptor if you want to check the saved fields. Second test: stub findByName to return an Optional holding an existing Greeting, call register, and use verify(repository, never()).save(any()) to confirm nothing was saved. Both rely on @ExtendWith(MockitoExtension.class), @Mock, and @InjectMocks, and no Spring context is started.
Exercise
A test stubs when(repository.findByName("ada")).thenReturn(...), but the service calls findByName("Ada"). With MockitoExtension, what does the test report, and why?
Show answer
The service gets Mockito's default return value for Optional, which is Optional.empty(), so the assertion on the greeting text fails. Strict stubs mode also reports that the "ada" stub was never used, and it flags a mismatch between the stubbed and the actual argument. The cause is the case difference between the two arguments.