Sub topic 3
Unit testing services with JUnit 5, Mockito, and AssertJ
This chapter assumes you know basic Java and JUnit-style testing, and that you understand Spring beans and dependency injection. You should also have spring-boot-starter-test on your test classpath, as covered in the previous chapter.
Why test services without Spring
A service class holds business logic. Its collaborators, such as repositories, are passed in through the constructor. That means you can create the service yourself and give it fake collaborators. No Spring context starts, so the test runs in milliseconds.
This is the cheapest test type in the pyramid. Use it for any logic you can reach without the framework: branching, calculations, and error handling.
The three libraries
| Library | Role in the test |
|---|---|
| JUnit 5 (Jupiter) | Finds and runs the test methods. |
| Mockito | Creates mock objects that stand in for collaborators. |
| AssertJ | Provides readable assertions through `assertThat(...)`. |
A first unit test
The service under test looks up a greeting by name through a repository. The test replaces the repository with a mock.
@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");
}
}The imports are org.junit.jupiter.api.Test, org.junit.jupiter.api.extension.ExtendWith, org.mockito.junit.jupiter.MockitoExtension, org.mockito.Mock, org.mockito.InjectMocks, java.util.Optional, and the static imports org.mockito.Mockito.when and org.assertj.core.api.Assertions.assertThat.
Each part has a job:
@ExtendWith(MockitoExtension.class)tells JUnit to create the mocks before each test.@Mockmakes a fakeGreetingRepository. By default every method returns an empty or null-like value.@InjectMocksbuilds a realGreetingServiceand passes the mock into its constructor.when(...).thenReturn(...)is stubbing. It defines what the mock returns for a given call.assertThat(...).isEqualTo(...)checks the result.
Testing the failure path
A good test suite covers errors too. Suppose the service throws GreetingNotFoundException when the repository returns an empty Optional. Mockito mocks that return Optional give Optional.empty() by default, but stub it explicitly so the test says what it means.
@Test
void throwsWhenGreetingIsMissing() {
when(repository.findByName("Grace")).thenReturn(Optional.empty());
assertThatThrownBy(() -> service.greetingFor("Grace"))
.isInstanceOf(GreetingNotFoundException.class)
.hasMessageContaining("Grace");
}assertThatThrownBy comes from org.assertj.core.api.Assertions. It runs the lambda and lets you assert on the exception that results.
Verifying interactions
Sometimes the result is not a return value but a call to a collaborator. Use verify for that.
@Test
void savesNewGreeting() {
service.create("Ada", "Hello, Ada");
verify(repository).save(any(Greeting.class));
}Prefer asserting on results. Verify calls only when the call is the behavior, such as saving or sending a message. Verifying every call ties the test to the implementation and makes refactoring painful.
Common errors
UnnecessaryStubbingException. The Mockito extension runs in strict mode. A stub that the code never uses fails the test. Remove the stub or fix the code path.NullPointerExceptionon the service. You forgot@ExtendWith(MockitoExtension.class), so@Mockand@InjectMockswere never processed.- Mocking the class under test. Mock collaborators only. The service must be real.
- Mocking simple value objects. Create a real
Greetinginstead of mocking it.
Exercise
A test with @Mock and @InjectMocks fails with a NullPointerException when it calls the service. The mock is declared correctly. What is the most likely cause, and how do you fix it?
Show answer
The test class is missing @ExtendWith(MockitoExtension.class), so the annotations are never processed and the fields stay null. Add the extension to the class.
Exercise
Why should you usually assert on a returned value rather than call verify on every repository method?
Show answer
Verifying every call couples the test to how the service is implemented. A refactor that keeps the behavior the same would still break the test. Use verify only when the call itself is the behavior, such as saving data.