JAVA-260 · Lesson 9 of 12 · 25 min
Testing Spring applications
▶ Video coming soon A video version of this lesson is on the way.
On Wednesday, March 15, Ingrid asked Hamza how he knew the booking service worked. He said he had tried it with curl. "And after you change something next week?" He would try it with curl again. Ingrid drew three boxes on the whiteboard, one small, one medium and one large, and wrote unit, slice and full beside them. This lesson covers testing a Spring Boot service at each of those three sizes: plain unit tests with fakes, test slices that start only the web layer or only the data layer, and full application tests over real HTTP against a real PostgreSQL database in a container.
Three sizes of test
A unit test checks one class with its collaborators replaced by fakes, and runs in milliseconds without Spring. A slice test starts a narrow part of the Spring application, such as the controllers with their JSON conversion, validation and error handling, or the repositories with a database, and replaces the rest. A full test starts the whole application on a random port and talks to it over HTTP. Each catches mistakes the others miss. Most tests should be unit tests because they are fast and precise, a good number should be slice tests, and a few full tests should prove that the pieces connect.
| Size | Starts | Catches | Speed |
|---|---|---|---|
| Unit | Nothing; plain new | Business rules: slot rules, stock levels, booking states | Milliseconds |
| Web slice (@WebMvcTest) | Controllers, advice, JSON, validation, security | Wrong status, wrong JSON shape, missing @Valid, URL rules | About a second |
| Data slice (@DataJpaTest) | Repositories, JPA, Flyway, a database | Wrong queries, mapping errors, migration problems | Seconds |
| Full (@SpringBootTest) | The whole application on a random port | Wiring and configuration mistakes between layers | Several seconds |
Unit tests with fakes
Constructor injection, from lesson 2, pays off here. BookingService receives its repository, its notifier and its clock through the constructor, so a test can pass an in-memory repository, a notifier that only records what it was asked to send, and a fixed clock. Nothing touches the network or the real time, so the test gives the same answer every run. The example writes the three fakes and a tiny test runner so that it can run without JUnit; the JUnit version follows.
import java.time.*;
import java.util.*;
public class Main {
record Booking(long id, String customer, String phone, LocalDateTime start) {}
interface BookingStore { Booking save(String customer, String phone, LocalDateTime start); boolean taken(LocalDateTime start); }
interface Notifier { void send(String phone, String text); }
static class BookingService {
private final BookingStore store; private final Notifier notifier; private final Clock clock;
BookingService(BookingStore store, Notifier notifier, Clock clock) { this.store = store; this.notifier = notifier; this.clock = clock; }
Booking book(String customer, String phone, LocalDateTime start) {
if (!start.isAfter(LocalDateTime.now(clock))) throw new IllegalArgumentException("start must be in the future");
if (start.getDayOfWeek() == DayOfWeek.MONDAY || start.getDayOfWeek() == DayOfWeek.SUNDAY)
throw new IllegalArgumentException("the shop is closed then");
if (store.taken(start)) throw new IllegalStateException("slot taken");
Booking b = store.save(customer, phone, start);
notifier.send(phone, "Booked: " + start.toLocalDate() + " " + start.toLocalTime() + ", ref " + b.id());
return b;
}
}
static class MemoryStore implements BookingStore {
final List<Booking> rows = new ArrayList<>();
public Booking save(String c, String p, LocalDateTime s) { Booking b = new Booking(2041 + rows.size(), c, p, s); rows.add(b); return b; }
public boolean taken(LocalDateTime s) { return rows.stream().anyMatch(b -> b.start().equals(s)); }
}
static class RecordingNotifier implements Notifier {
final List<String> sent = new ArrayList<>();
public void send(String phone, String text) { sent.add(phone + " " + text); }
}
static int passed = 0, failed = 0;
static void test(String name, Runnable body) {
try { body.run(); passed++; System.out.println("PASS " + name); }
catch (AssertionError | RuntimeException e) { failed++; System.out.println("FAIL " + name + ": " + e.getMessage()); }
}
static void check(boolean ok, String message) { if (!ok) throw new AssertionError(message); }
public static void main(String[] args) {
Clock clock = Clock.fixed(Instant.parse("2028-03-15T23:00:00Z"), ZoneId.of("America/Toronto"));
LocalDateTime saturday = LocalDateTime.of(2028, 5, 6, 10, 30);
test("a valid booking is saved and the customer is texted", () -> {
MemoryStore store = new MemoryStore(); RecordingNotifier sms = new RecordingNotifier();
Booking b = new BookingService(store, sms, clock).book("Ana Ferreira", "614-555-0142", saturday);
check(b.id() == 2041, "id was " + b.id());
check(sms.sent.equals(List.of("614-555-0142 Booked: 2028-05-06 10:30, ref 2041")), "sent " + sms.sent);
});
test("a taken slot is refused and nobody is texted twice", () -> {
MemoryStore store = new MemoryStore(); RecordingNotifier sms = new RecordingNotifier();
BookingService service = new BookingService(store, sms, clock);
service.book("Ana Ferreira", "614-555-0142", saturday);
try { service.book("Dev Okafor", "614-555-0199", saturday); check(false, "no exception"); }
catch (IllegalStateException expected) { check(sms.sent.size() == 1, "sent " + sms.sent.size()); }
});
test("Mondays are refused", () -> {
try { new BookingService(new MemoryStore(), new RecordingNotifier(), clock).book("Ana", "614-555-0142", saturday.plusDays(2)); check(false, "no exception"); }
catch (IllegalArgumentException expected) { check(expected.getMessage().contains("closed"), expected.getMessage()); }
});
test("a start in the past is refused", () -> {
try { new BookingService(new MemoryStore(), new RecordingNotifier(), clock).book("Ana", "614-555-0142", LocalDateTime.of(2028, 3, 14, 10, 0)); check(false, "no exception"); }
catch (IllegalArgumentException expected) { check(true, ""); }
});
System.out.println(passed + " passed, " + failed + " failed");
}
}PASS a valid booking is saved and the customer is texted PASS a taken slot is refused and nobody is texted twice PASS Mondays are refused PASS a start in the past is refused 4 passed, 0 failed
What this code does
Each test builds a fresh service from fakes: a store that keeps bookings in a list, a notifier that records messages instead of sending them, and a clock fixed at an evening in March 2028. Because the notifier only records, the tests can check exactly which text would have gone to the customer, and that a refused booking sends nothing. The fixed clock makes the past-date rule give the same answer on every run, which a test that used the real time could not promise.
class BookingServiceTest {
Clock clock = Clock.fixed(Instant.parse("2028-03-15T23:00:00Z"), ZoneId.of("America/Toronto"));
MemoryBookingStore store = new MemoryBookingStore();
RecordingNotifier sms = new RecordingNotifier();
BookingService service = new BookingService(store, sms, clock);
@Test
void takenSlotIsRefused() {
LocalDateTime saturday = LocalDateTime.of(2028, 5, 6, 10, 30);
service.book(new NewBooking("Ana Ferreira", "555-555-0142", saturday));
assertThatThrownBy(() -> service.book(new NewBooking("Dev Okafor", "555-555-0199", saturday)))
.isInstanceOf(SlotTaken.class);
assertThat(sms.sent()).hasSize(1);
}
}What this code does
The JUnit 6 test has no Spring annotations at all: it creates the service with new, passing the same kinds of fakes. AssertJ's assertThatThrownBy checks the exception type, and assertThat checks that only one message was recorded. A test like this runs in a few milliseconds.
Hand-written fakes are often clearer than mocks, because they behave like the real thing in a small way. Mockito is the alternative when a fake would be large or when the test must check exactly how a collaborator was called. Spring Boot's test starter includes JUnit, AssertJ, Mockito and the Spring test support, so no extra dependencies are needed.
Web slices
A @WebMvcTest starts only what the web layer needs: the controller under test, the @RestControllerAdvice classes, Jackson, validation and the security filter chain. Services are not created, so the test supplies them, usually as Mockito mocks declared with @MockitoBean, which replaced the older @MockBean. Spring Boot 4 offers MockMvcTester, an AssertJ-friendly way to send requests to the controllers without a real network, and RestTestClient, a newer client that can run against MockMvc or a live server. The idea is easy to see in plain Java: the handler is a function from a request to a response, and a slice test calls it directly.
import java.util.*;
import java.util.function.Function;
public class Main {
record Request(String method, String path, String body) {}
record Response(int status, String contentType, String body) {}
interface BookingService { String find(long id); }
static class BookingNotFound extends RuntimeException { BookingNotFound(long id) { super("No repair booking " + id); } }
static Function<Request, Response> controller(BookingService service) {
return req -> {
if (!req.method().equals("GET") || !req.path().startsWith("/api/v1/repair-bookings/"))
return new Response(404, "application/problem+json", "{\"status\":404}");
String tail = req.path().substring("/api/v1/repair-bookings/".length());
if (!tail.matches("\\d+"))
return new Response(400, "application/problem+json", "{\"status\":400,\"detail\":\"id must be a number\"}");
try {
return new Response(200, "application/json", service.find(Long.parseLong(tail)));
} catch (BookingNotFound e) {
return new Response(404, "application/problem+json", "{\"status\":404,\"detail\":\"" + e.getMessage() + "\"}");
}
};
}
public static void main(String[] args) {
BookingService stub = id -> {
if (id == 2041) return "{\"id\":2041,\"status\":\"BOOKED\"}";
throw new BookingNotFound(id);
};
Function<Request, Response> web = controller(stub);
Object[][] cases = {
{"/api/v1/repair-bookings/2041", 200}, {"/api/v1/repair-bookings/99999", 404}, {"/api/v1/repair-bookings/abc", 400}};
for (Object[] c : cases) {
Response r = web.apply(new Request("GET", (String) c[0], ""));
String verdict = r.status() == (int) c[1] ? "PASS" : "FAIL";
System.out.println(verdict + " GET " + c[0] + " -> " + r.status() + " " + r.contentType() + " " + r.body());
}
}
}PASS GET /api/v1/repair-bookings/2041 -> 200 application/json {"id":2041,"status":"BOOKED"}
PASS GET /api/v1/repair-bookings/99999 -> 404 application/problem+json {"status":404,"detail":"No repair booking 99999"}
PASS GET /api/v1/repair-bookings/abc -> 400 application/problem+json {"status":400,"detail":"id must be a number"}What this code does
The controller is a function from a request to a response, and the test calls it directly with a stub service that knows only booking 2041. That checks the web layer's own decisions, the status code, the content type and the error body, without a network, a database or the real service. MockMvc does the same for a Spring controller, sending requests through the DispatcherServlet in memory.
@WebMvcTest(RepairBookingController.class)
@Import(SecurityConfig.class)
class RepairBookingControllerTest {
@Autowired MockMvcTester mvc;
@MockitoBean BookingService bookings;
@Test
void invalidBookingIsAProblemDocument() {
assertThat(mvc.post().uri("/api/v1/repair-bookings")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"customer\":\"\",\"phone\":\"asap\",\"start\":\"2019-06-01T10:00\",\"bike\":\"Trek FX 2\"}"))
.hasStatus(HttpStatus.BAD_REQUEST)
.hasContentType(MediaType.APPLICATION_PROBLEM_JSON)
.bodyJson().extractingPath("$.errors.length()").isEqualTo(3);
verifyNoInteractions(bookings);
}
@Test
@WithMockUser(roles = "STAFF")
void staffCanListADay() {
when(bookings.forDay(LocalDate.of(2028, 5, 6))).thenReturn(List.of());
assertThat(mvc.get().uri("/api/v1/repair-bookings?date=2028-05-06")).hasStatusOk();
}
@Test
void visitorsCannotListADay() {
assertThat(mvc.get().uri("/api/v1/repair-bookings?date=2028-05-06")).hasStatus(HttpStatus.UNAUTHORIZED);
}
}What this code does
@WebMvcTest starts just this controller with the web infrastructure, and @Import brings in the real security rules so they are tested too. The first test proves that @Valid and the advice class turn Kofi's bad request into a problem document with three errors, and that the service was never called. @WithMockUser runs a test as a signed-in staff member, so the last two tests check the access table from lesson 7 in both directions.
Data slices with a real database
A @DataJpaTest starts the repositories, JPA and Flyway, and by default rolls back each test's changes. The question is which database. An in-memory H2 database is fast but is not PostgreSQL: a query that works on H2 can fail on the server, and the other way round. Testcontainers starts a real PostgreSQL in a Docker container for the tests, and Spring Boot's @ServiceConnection points the data source at it automatically. Leif's build server already ran Docker, so the team chose real PostgreSQL for every data test.
@DataJpaTest
@Testcontainers
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class PartRepositoryTest {
@Container
@ServiceConnection
static PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:18");
@Autowired PartRepository parts;
@Test
void lowStockUsesReorderLevel() {
parts.save(Part.of("CHAIN-11", "11-speed chain", "C2", 3, 5));
parts.save(Part.of("BELL", "Brass bell", "A3", 14, 4));
assertThat(parts.findLowStock()).extracting(Part::code).containsExactly("CHAIN-11");
}
}What this code does
The @Container field starts a PostgreSQL container once for the test class, and @ServiceConnection gives Spring Boot its address, user and password, so no URL is written anywhere. Replace.NONE stops Spring from swapping in an embedded database. Flyway runs V1 to V5 against the container first, so the test also proves that the migrations work on the real database.
Full tests over HTTP
A @SpringBootTest with webEnvironment = RANDOM_PORT starts the whole application on a free port, exactly as the JDK examples in this course do with port 0. The test then sends real HTTP requests, which proves that the beans are wired, the configuration loads, the security rules apply, the JSON is right and the database is reached. The example runs the same idea in plain Java: it starts a booking server, then runs three checks against it over HTTP, including the full slot that must give 409.
import com.sun.net.httpserver.HttpServer;
import java.net.*;
import java.net.http.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
Set<String> taken = new TreeSet<>();
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/api/v1/repair-bookings", ex -> {
String start = new String(ex.getRequestBody().readAllBytes(), StandardCharsets.UTF_8).trim();
int status;
synchronized (taken) { status = taken.add(start) ? 201 : 409; }
ex.sendResponseHeaders(status, -1);
ex.close();
});
server.start();
int passed = 0;
try {
HttpClient client = HttpClient.newHttpClient();
URI uri = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/api/v1/repair-bookings");
String[][] steps = {{"2028-05-06T10:30", "201"}, {"2028-05-06T11:00", "201"}, {"2028-05-06T10:30", "409"}};
for (String[] s : steps) {
HttpRequest req = HttpRequest.newBuilder(uri).POST(HttpRequest.BodyPublishers.ofString(s[0])).build();
int got = client.send(req, HttpResponse.BodyHandlers.discarding()).statusCode();
boolean ok = got == Integer.parseInt(s[1]);
if (ok) passed++;
System.out.println((ok ? "PASS" : "FAIL") + " POST " + s[0] + " expected " + s[1] + ", got " + got);
}
} finally {
server.stop(0);
}
System.out.println(passed + " of 3 passed; slots taken: " + taken);
}
}PASS POST 2028-05-06T10:30 expected 201, got 201 PASS POST 2028-05-06T11:00 expected 201, got 201 PASS POST 2028-05-06T10:30 expected 409, got 409 3 of 3 passed; slots taken: [2028-05-06T10:30, 2028-05-06T11:00]
What this code does
The server is started on a free port before the checks and stopped afterwards in the finally block, which is what @SpringBootTest does around a test class. Each check sends a real POST and compares the status with the expected one, so the third request for 10:30 must get 409. The taken set is synchronized because the server's handler and the main thread both touch it.
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureRestTestClient
@Testcontainers
class BookingApiIT {
@Container @ServiceConnection
static PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:18");
@Autowired RestTestClient http;
@Test
void secondBookingForTheSameSlotIsAConflict() {
var body = Map.of("customer", "Ana Ferreira", "phone", "555-555-0142",
"start", "2028-05-06T10:30", "bike", "Trek FX 2");
http.post().uri("/api/v1/repair-bookings").body(body).exchange()
.expectStatus().isCreated()
.expectHeader().exists("Location");
http.post().uri("/api/v1/repair-bookings").body(body).exchange()
.expectStatus().isEqualTo(409);
}
}What this code does
RANDOM_PORT starts the real embedded server on a free port, and RestTestClient sends real HTTP requests to it. Testcontainers supplies PostgreSQL, so the booking is stored by the real repository through the real migrations. The test checks the whole path that the website will use: 201 with a Location header, then 409 for the same slot.
Spring caches the application context between tests that use the same configuration, so a suite of slice tests does not start Spring from scratch for every class. Each different set of @MockitoBean fields or properties makes a new context, though, and a suite with many small variations can become slow. Keeping test configurations few and alike is the fix.
./gradlew test> Task :test BookingServiceTest > takenSlotIsRefused() PASSED RepairBookingControllerTest > invalidBookingIsAProblemDocument() PASSED RepairBookingControllerTest > staffCanListADay() PASSED RepairBookingControllerTest > visitorsCannotListADay() PASSED PartRepositoryTest > lowStockUsesReorderLevel() PASSED BookingApiIT > secondBookingForTheSameSlotIsAConflict() PASSED BUILD SUCCESSFUL in 24s
What this code does
Gradle runs all three sizes of test and prints a summary. The Testcontainers tests pull the PostgreSQL image the first time, which makes the first run slower.
Try it yourself
A recording fake
Write RecordingNotifier, a Notifier that keeps every message in a list instead of sending it, so the test in main passes.
The program must print PASS reminder sent once and the recorded message.
import java.util.*;
public class Main {
interface Notifier { void send(String phone, String text); }
static class RecordingNotifier implements Notifier {
public void send(String phone, String text) { }
List<String> sent() { return List.of(); }
}
static void remindTomorrow(Notifier n, String phone, String time) {
n.send(phone, "Reminder: your repair is booked for tomorrow at " + time);
}
public static void main(String[] args) {
RecordingNotifier fake = new RecordingNotifier();
remindTomorrow(fake, "555-555-0142", "10:30");
System.out.println((fake.sent().size() == 1 ? "PASS" : "FAIL") + " reminder sent once");
System.out.println(fake.sent());
}
}Try it yourself
Test the opening hours
isBookable should accept starts from Tuesday to Saturday between 09:00 and 15:00 inclusive, on the hour or the half hour.
Fix the bug in isBookable so that all five checks print PASS.
import java.time.*;
public class Main {
static boolean isBookable(LocalDateTime t) {
DayOfWeek d = t.getDayOfWeek();
boolean openDay = d != DayOfWeek.SUNDAY;
boolean inHours = !t.toLocalTime().isBefore(LocalTime.of(9, 0)) && t.toLocalTime().isBefore(LocalTime.of(15, 0));
boolean onSlot = t.getMinute() == 0 || t.getMinute() == 30;
return openDay && inHours && onSlot;
}
static void expect(String name, boolean want, LocalDateTime t) {
System.out.println((isBookable(t) == want ? "PASS " : "FAIL ") + name);
}
public static void main(String[] args) {
expect("Saturday 10:30 is bookable", true, LocalDateTime.of(2028, 5, 6, 10, 30));
expect("Saturday 15:00 is the last start", true, LocalDateTime.of(2028, 5, 6, 15, 0));
expect("Monday is closed", false, LocalDateTime.of(2028, 5, 8, 10, 30));
expect("08:30 is too early", false, LocalDateTime.of(2028, 5, 6, 8, 30));
expect("10:15 is not a slot", false, LocalDateTime.of(2028, 5, 6, 10, 15));
}
}The next week, when Hamza changed the slot rules for the capstone, the hours test failed at once and pointed to the line. "That," said Ingrid, "is the answer to my question."
Common mistakes
MistakeTesting everything through a full @SpringBootTest.
InsteadTest rules with fast unit tests and keep full tests for wiring.
MistakeCalling LocalDateTime.now() inside services.
InsteadInject a Clock and fix it in tests.
MistakeTesting repositories against H2 when production runs PostgreSQL.
InsteadUse Testcontainers with the same database and the real migrations.
MistakeLeaving security out of web slice tests.
InsteadImport the real SecurityFilterChain and test both allowed and refused callers.
MistakeGiving every test class its own unusual configuration.
InsteadKeep test configurations alike so Spring can reuse cached contexts.
Summary and key terms
- A Spring Boot service is tested at three sizes.
- Unit tests create classes with new and pass fakes and a fixed Clock, which constructor injection makes easy. @WebMvcTest slices start the controllers, advice, JSON, validation and security, with services replaced by @MockitoBean mocks, and MockMvcTester or RestTestClient sends requests in memory; @WithMockUser runs a test as a signed-in user. @DataJpaTest slices start repositories, JPA and Flyway, ideally against PostgreSQL from Testcontainers wired by @ServiceConnection. @SpringBootTest with RANDOM_PORT starts the whole application on a free port for real HTTP tests.
- Most tests should be unit tests, with fewer slices and a handful of full tests; Spring caches contexts between tests with the same configuration.
- Unit test
- A test of one class with its collaborators replaced, without Spring.
- Fake
- A small working implementation used in tests, such as an in-memory store.
- Mock
- A test object that records calls and returns programmed answers, usually made with Mockito.
- Test slice
- A test that starts one layer of a Spring application, such as @WebMvcTest.
- @MockitoBean
- Replaces a bean in a Spring test with a Mockito mock.
- MockMvcTester
- An AssertJ-style tool for sending requests to Spring MVC controllers in memory.
- RestTestClient
- A Spring test client for REST calls against MockMvc or a running server.
- Testcontainers
- A library that starts real services such as PostgreSQL in Docker containers for tests.
- @ServiceConnection
- Connects Spring Boot to a Testcontainers service without writing its address.
- RANDOM_PORT
- A @SpringBootTest setting that starts the real server on a free port.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Which annotation starts only the web layer for a test?
Show answer
@WebMvcTest.
How does a unit test control the current time?
Show answer
It passes a fixed Clock to the class under test.
Why use Testcontainers rather than H2 for repository tests?
Show answer
It runs the same database as production, so queries and migrations behave the same.
Which annotation replaces a bean with a Mockito mock in a Spring test?
Show answer
@MockitoBean.
What does RANDOM_PORT do?
Show answer
Starts the real embedded server on a free port for the test.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.