TExcelTAD
Home › Spring Boot › Testing

Testing

spring-boot-starter-test gives you JUnit 5, AssertJ, Mockito, JSONPath and Spring's test support in one dependency. The art is choosing the right kind of test: plain unit tests for logic, slice tests (@WebMvcTest, @DataJpaTest) for one layer, and a few full @SpringBootTest integration tests.

The test pyramid for a Spring Boot app

Test type Starts Speed Use for
plain unit test nothing — just new milliseconds services, mappers, validation logic
@WebMvcTest MVC layer only (controllers, advice, Jackson) ~1 s status codes, JSON shape, validation errors
@DataJpaTest JPA, repositories, embedded DB ~2 s custom queries, mappings
@SpringBootTest the whole application several s end-to-end wiring, a few happy paths

Unit tests need no Spring

Because services use constructor injection, you can test them with plain objects. This test-style program uses a hand-written fake repository and simple assertions:

java · try it yourself
import java.util.*;

class TaskNotFoundException extends RuntimeException {
    TaskNotFoundException(long id) { super("Task " + id + " not found"); }
}

record Task(long id, String title, boolean done) {
    Task complete() { return new Task(id, title, true); }
}

interface TaskRepository {
    Optional<Task> findById(long id);
    Task save(Task t);
}

class TaskService {
    private final TaskRepository repo;
    TaskService(TaskRepository repo) { this.repo = repo; }
    Task complete(long id) {
        Task t = repo.findById(id).orElseThrow(() -> new TaskNotFoundException(id));
        return repo.save(t.complete());
    }
}

class FakeRepo implements TaskRepository {
    final Map<Long, Task> data = new HashMap<>();
    int saves = 0;
    public Optional<Task> findById(long id) { return Optional.ofNullable(data.get(id)); }
    public Task save(Task t) { saves++; data.put(t.id(), t); return t; }
}

class Main {
    static int passed = 0, failed = 0;

    static void check(String name, boolean condition) {
        if (condition) passed++; else failed++;
        System.out.println((condition ? "PASS " : "FAIL ") + name);
    }

    public static void main(String[] args) {
        // completeMarksTaskDone
        FakeRepo repo = new FakeRepo();
        repo.data.put(1L, new Task(1, "Write tests", false));
        Task result = new TaskService(repo).complete(1);
        check("completeMarksTaskDone", result.done() && repo.saves == 1);

        // completeUnknownTaskThrows
        try {
            new TaskService(new FakeRepo()).complete(99);
            check("completeUnknownTaskThrows", false);
        } catch (TaskNotFoundException e) {
            check("completeUnknownTaskThrows", e.getMessage().equals("Task 99 not found"));
        }

        System.out.println("Tests run: " + (passed + failed) + ", Failures: " + failed);
    }
}
PASS completeMarksTaskDone
PASS completeUnknownTaskThrows
Tests run: 2, Failures: 0

In a real project the same tests are JUnit methods using AssertJ and (optionally) Mockito:

java
class TaskServiceTest {
    TaskRepository repo = mock(TaskRepository.class);
    TaskService service = new TaskService(repo);

    @Test
    void completeMarksTaskDone() {
        when(repo.findById(1L)).thenReturn(Optional.of(new Task(1, "Write tests", false)));
        when(repo.save(any())).thenAnswer(inv -> inv.getArgument(0));

        assertThat(service.complete(1).done()).isTrue();
        verify(repo).save(any());
    }

    @Test
    void completeUnknownTaskThrows() {
        when(repo.findById(99L)).thenReturn(Optional.empty());
        assertThatThrownBy(() -> service.complete(99))
            .isInstanceOf(TaskNotFoundException.class)
            .hasMessage("Task 99 not found");
    }
}

Controller slice tests with MockMvc

@WebMvcTest starts only the web layer and gives you MockMvc, which sends fake HTTP requests without a real server. Collaborators are replaced with @MockitoBean (new in Boot 3.4, replacing the deprecated @MockBean):

java
@WebMvcTest(TaskController.class)
class TaskControllerTest {

    @Autowired MockMvc mvc;
    @MockitoBean TaskService service;

    @Test
    void getReturnsTask() throws Exception {
        when(service.get(1L)).thenReturn(new TaskResponse(1, "Write tests", null, Priority.HIGH, false, "Website"));

        mvc.perform(get("/api/tasks/1"))
           .andExpect(status().isOk())
           .andExpect(jsonPath("$.title").value("Write tests"))
           .andExpect(jsonPath("$.priority").value("HIGH"));
    }

    @Test
    void invalidBodyReturns400WithFieldErrors() throws Exception {
        mvc.perform(post("/api/tasks").contentType(MediaType.APPLICATION_JSON).content("{\"title\":\"\"}"))
           .andExpect(status().isBadRequest())
           .andExpect(jsonPath("$.errors.title").value("must not be blank"));
    }

    @Test
    void unknownTaskReturns404() throws Exception {
        when(service.get(99L)).thenThrow(new TaskNotFoundException(99));
        mvc.perform(get("/api/tasks/99"))
           .andExpect(status().isNotFound())
           .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON));
    }
}
bash · try it yourself
./mvnw test -Dtest=TaskControllerTest
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.example.tasks.task.TaskControllerTest
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.482 s -- in com.example.tasks.task.TaskControllerTest
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------

When an expectation fails, MockMvc prints the whole request and response, which usually points straight at the problem:

bash · try it yourself
./mvnw -q test -Dtest=TaskControllerTest#getReturnsTask
[ERROR] Failures:
[ERROR]   TaskControllerTest.getReturnsTask:31 JSON path "$.priority" expected:<HIGH> but was:<MEDIUM>
[ERROR] Tests run: 1, Failures: 1, Errors: 0, Skipped: 0

Repository slice tests

java
@DataJpaTest
class TaskRepositoryTest {
    @Autowired TaskRepository repo;

    @Test
    void findsOpenTasksOrderedByDueDate() {
        repo.save(new Task("later", Priority.LOW, LocalDate.of(2025, 12, 1)));
        repo.save(new Task("sooner", Priority.LOW, LocalDate.of(2025, 11, 1)));
        assertThat(repo.findByDoneFalseOrderByDueDateAsc())
            .extracting(Task::getTitle).containsExactly("sooner", "later");
    }
}

Each @DataJpaTest method runs in a transaction that is rolled back afterwards, so tests don't affect each other.

Full integration tests

java
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class TaskApiIT {
    @Autowired TestRestTemplate http;

    @Test
    void createThenFetch() {
        var created = http.postForEntity("/api/tasks", Map.of("title", "IT", "priority", "LOW"), TaskResponse.class);
        assertThat(created.getStatusCode()).isEqualTo(HttpStatus.CREATED);
        var fetched = http.getForObject(created.getHeaders().getLocation(), TaskResponse.class);
        assertThat(fetched.title()).isEqualTo("IT");
    }
}

Tip: For tests against a real PostgreSQL, add Testcontainers and annotate a container bean with @ServiceConnection — Boot then points the datasource at the container automatically.

Test yourself

Which annotation starts only the MVC layer for fast controller tests?

  1. @SpringBootTest
  2. @WebMvcTest
  3. @DataJpaTest
  4. @MockitoBean

In Spring Boot 3.4+, how do you replace a bean with a Mockito mock in a slice test?

  1. @MockitoBean
  2. @Fake
  3. @InjectMocks
  4. @Stub

What happens to data written in a @DataJpaTest test method?

  1. It is committed permanently
  2. It is rolled back after each test
  3. It is written to a file
  4. It is shared with the next test