Skip to content
Tutorials Center
My learning

Topics

Lesson 76 of 119 ยท Spring Boot

Testing Spring Boot Applications

Test Spring Boot apps at the right level - plain unit tests, @WebMvcTest with MockMvc, @DataJpaTest, @SpringBootTest, @MockitoBean, context caching and Testcontainers.

A Spring Boot application has many layers: controllers, JSON mapping, validation, services, repositories, the database, security. Testing all of them only through a fully started application is slow and makes failures hard to locate. Testing each class in isolation with mocks misses the bugs that live between layers, like a wrong JSON field name or a query that doesn't run on the real database. Good Spring Boot test suites mix levels on purpose.

This lesson walks through those levels: plain unit tests without Spring, slice tests that start only one layer (@WebMvcTest with MockMvc, @DataJpaTest), full integration tests with @SpringBootTest, and Testcontainers for real databases. You'll learn how to replace beans with @MockitoBean, and why Spring's context caching decides how fast your suite is. Each Spring snippet is read-only, and each idea also comes with a runnable JUnit test on this page that reproduces it in plain Java. You should know Unit Testing with JUnit 6, Test Doubles and Mockito and Integration Testing.

The test toolbox

One dependency brings everything:

XML
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
</dependency>

It includes JUnit Jupiter, Spring Test and Spring Boot Test, AssertJ (fluent assertions), Hamcrest, Mockito, JSONassert and JsonPath. Spring Initializr adds it to every project, together with one test that starts the whole application.

The main test annotations, from smallest to largest:

Annotation Starts Typical use Speed
none (plain JUnit) Nothing Services, domain logic, mappers Milliseconds
@JsonTest Jackson only JSON shape of DTOs Fast
@WebMvcTest Spring MVC layer for given controllers Mappings, status codes, validation, JSON, security rules Fast
@DataJpaTest JPA, repositories, a database Queries, mappings, constraints Medium
@RestClientTest RestClient / RestTemplate + a mock server Clients for other APIs Fast
@SpringBootTest The whole application End-to-end flows, wiring, configuration Slowest

Spring Boot 4 moved the test slices into technology-specific modules, each with a matching test starter (for example spring-boot-starter-webmvc-test for @WebMvcTest and spring-boot-starter-data-jpa-test for @DataJpaTest). The annotations work as described here, but their packages differ from Boot 3, so let your IDE add the imports. The snippets below omit the imports for that reason.

Level 1: unit tests without Spring

If you use constructor injection, your services are plain Java objects. Test them with new and a hand-written fake or a Mockito mock. No context starts, so these tests run in milliseconds, and they should be the majority of your suite.

Java
class LoanServiceTest {
    private final InMemoryBookRepository books = new InMemoryBookRepository();
    private final LoanService service = new LoanService(books, Clock.fixed(Instant.parse("2026-03-01T10:00:00Z"), ZoneOffset.UTC));

    @Test
    void lendingSetsDueDateTwoWeeksAhead() {
        books.save(new Book(1L, "Dune", null));
        Loan loan = service.lend(1L, "ada");
        assertThat(loan.due()).isEqualTo(LocalDate.of(2026, 3, 15));
    }
}

Here is a runnable version: a LoanService with business rules, a fake repository, a fixed Clock, and five tests. The small runTests helper at the bottom plays the role of Maven's Surefire plugin and prints one line per test.

Java Unit tests: a service without Spring

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Note the injected Clock. Code that calls LocalDate.now() directly can't be tested reliably; code that receives a Clock (as a Spring bean in production, a fixed clock in tests) can. Designing for testability like this is most of the work. The order of the result lines may differ from the source order, because JUnit doesn't guarantee method order.

Level 2: @WebMvcTest and MockMvc

Controllers are thin, but a lot can go wrong around them: the path, the HTTP method, parameter binding, validation, the JSON field names, the status code, the error body, security rules. A plain unit test that calls controller.get(1L) checks none of that. @WebMvcTest starts only the web layer (your controllers, @ControllerAdvice, converters, filters and security config) and gives you MockMvc, which sends fake requests through the real DispatcherServlet without opening a network port:

Java
@WebMvcTest(BookController.class)
class BookControllerTest {

    @Autowired MockMvc mvc;
    @MockitoBean BookService books;                      // replaces the real service in the context

    @Test
    void returnsBookAsJson() throws Exception {
        given(books.findById(1L)).willReturn(Optional.of(new Book(1L, "Dune", "Frank Herbert", 1965)));

        mvc.perform(get("/api/books/1").accept(MediaType.APPLICATION_JSON))
           .andExpect(status().isOk())
           .andExpect(content().contentType(MediaType.APPLICATION_JSON))
           .andExpect(jsonPath("$.title").value("Dune"))
           .andExpect(jsonPath("$.year").value(1965));
    }

    @Test
    void rejectsBlankTitle() throws Exception {
        mvc.perform(post("/api/books")
                .contentType(MediaType.APPLICATION_JSON)
                .content("""
                    {"title": " ", "author": "Frank Herbert", "year": 1965}"""))
           .andExpect(status().isBadRequest())
           .andExpect(jsonPath("$.errors[0].field").value("title"));

        then(books).shouldHaveNoInteractions();          // the service was never called
    }
}

Key points:

  • Services and repositories are not in a @WebMvcTest context. Provide them with @MockitoBean (Spring Framework 6.2+, in org.springframework.test.context.bean.override.mockito). It replaces the older Boot annotation @MockBean, which was deprecated in Boot 3.4 and removed in Boot 4. @MockitoSpyBean wraps a real bean instead.
  • jsonPath("$.title") checks the JSON that a real client would see, so a renamed field or a missing @JsonProperty breaks the test, as it should.
  • Since Spring Framework 6.2 there is also MockMvcTester, an AssertJ-style variant: assertThat(mvc.get().uri("/api/books/1")).hasStatusOk().bodyJson().extractingPath("$.title").isEqualTo("Dune").

The program below reproduces the idea: a MockMvc-like tester that calls the web layer in-process (no socket), a fluent perform(...).andExpect(...) API, JSON path checks with Jackson's JsonNode, and a hand-written stub service that records its calls, playing the part of @MockitoBean.

Java A MockMvc-style test of the web layer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The last test fails on purpose, to show what a good failure message looks like: it names the missing JSON path and prints the actual body. That's the experience MockMvc and jsonPath give you in a real project. Delete that test (or fix the path to /title) and all tests pass.

Level 3: @DataJpaTest

@DataJpaTest starts JPA, Hibernate, your repositories and a DataSource, but no web layer and no services. Two behaviors matter:

  • Each test runs in a transaction that is rolled back at the end. Tests can insert and delete freely without affecting each other, and there's nothing to clean up.
  • By default, Boot replaces your DataSource with an embedded database (H2, if it's on the test classpath). That's fast, but H2 is not PostgreSQL: native queries, JSON columns, locking behavior and some functions differ. For those, use @AutoConfigureTestDatabase(replace = Replace.NONE) with Testcontainers (below).
Java
@DataJpaTest
class BookRepositoryTest {

    @Autowired BookRepository books;
    @Autowired TestEntityManager em;            // helper to set up data and flush

    @Test
    void findsByAuthorNewestFirst() {
        em.persist(new Book("The Dispossessed", "Ursula K. Le Guin", 1974));
        em.persist(new Book("The Left Hand of Darkness", "Ursula K. Le Guin", 1969));
        em.flush();                             // send SQL now, so query errors show up here

        assertThat(books.findByAuthorOrderByYearDesc("Ursula K. Le Guin"))
            .extracting(Book::getTitle)
            .containsExactly("The Dispossessed", "The Left Hand of Darkness");
    }
}

Because of the rollback, @DataJpaTest can hide bugs that only appear at commit, such as deferred constraint violations, or a missing flush. Calling em.flush() (or saveAndFlush) in the test forces the SQL to run. Also, putting @Transactional on @SpringBootTest tests gives the same rollback behavior, but then your service's own transaction boundaries are no longer what is being tested.

This program reproduces the rollback-per-test behavior with JDBC on H2: the schema is created once, each test opens a transaction in @BeforeEach and rolls it back in @AfterEach. The tests are ordered so that the one that deletes everything runs first, and the later tests still see the seeded rows.

Java Repository tests with rollback after each test

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The constraint test is valuable: it proves the database itself enforces uniqueness, which no mock can tell you. That's the kind of fact repository tests exist for.

Level 4: @SpringBootTest

@SpringBootTest starts the whole application context, with all your beans and configuration. Use it for a few end-to-end tests of important flows, and to check that the application wires together at all (the generated contextLoads() test).

Java
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
class LibraryApplicationIT {

    @LocalServerPort int port;                // the real embedded server's port

    @Test
    void lendAndReturnABook() {
        RestClient client = RestClient.create("http://localhost:" + port);
        Book created = client.post().uri("/api/books").contentType(MediaType.APPLICATION_JSON)
            .body(new NewBook("Dune", "Frank Herbert", 1965))
            .retrieve().body(Book.class);

        ResponseEntity<Void> loan = client.post().uri("/api/books/{id}/loans", created.id())
            .body(Map.of("borrower", "ada")).retrieve().toBodilessEntity();

        assertThat(loan.getStatusCode()).isEqualTo(HttpStatus.CREATED);
    }
}

The webEnvironment decides what kind of server you get:

  • MOCK (default): a mock servlet environment, no real port; use @AutoConfigureMockMvc and MockMvc.
  • RANDOM_PORT: a real embedded server on a free port, called over real HTTP. Spring Framework 7 also offers RestTestClient for this; Boot 3 projects often use TestRestTemplate.
  • NONE: no web environment, for batch jobs and message consumers.

Other tools you will use with full tests: @ActiveProfiles("test") to load application-test.properties, @TestPropertySource or the properties attribute for one-off settings, @TestConfiguration classes for extra beans (a fixed Clock), and @DynamicPropertySource to set properties computed at runtime, such as a container's URL.

Context caching: why test suites get slow

Starting a Spring context takes seconds. Spring Test therefore caches contexts and reuses one context for every test class with the same configuration: the same annotations, the same @MockitoBeans, the same properties and profiles. A suite with 200 test classes that share three configurations starts three contexts.

The cache is easy to defeat without noticing. Every test class with a different set of @MockitoBean fields, a different @TestPropertySource, or @DirtiesContext (which throws the context away after use) gets its own context. If your suite starts dozens of contexts, look for these differences and standardize them, for example with a shared abstract base class or a custom composed annotation that carries the common configuration. Boot logs each context start, so counting the banners in the test output is a quick check.

Testcontainers: the real database in tests

Testcontainers starts real services (PostgreSQL, MySQL, Kafka, Redis) in Docker for the duration of the tests. Spring Boot integrates with it through @ServiceConnection, which reads the container's host, port and credentials and configures the DataSource automatically:

Java
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)   // don't swap in H2
@Testcontainers
class BookRepositoryPostgresTest {

    @Container
    @ServiceConnection
    static PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:17-alpine");

    @Autowired BookRepository books;

    @Test
    void fullTextSearchWorksOnPostgres() { ... }
}

The same containers can also be used at development time (./mvnw spring-boot:test-run with a TestApplication class that declares them), so developers don't need a locally installed database at all. Testcontainers needs Docker on the developer machine and in CI; container startup adds a few seconds, which context caching and a static container shared across tests keep under control.

A practical test strategy

  • Many unit tests for domain logic and services: plain JUnit, fakes or Mockito mocks, injected Clocks.
  • A @WebMvcTest per controller for mappings, status codes, validation, error bodies, JSON names and security rules.
  • @DataJpaTest for custom queries, ideally against the real database engine with Testcontainers. Don't test Spring Data's own save/findById; test your queries.
  • A handful of @SpringBootTests for critical flows end to end, plus contextLoads().
  • Keep test configuration uniform so contexts are cached, and run the slow tests in a separate Maven/Gradle task if needed (*IT classes with the Failsafe plugin).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A test is annotated with @WebMvcTest(BookController.class), and the controller needs a BookService. The test fails at startup with "No qualifying bean of type BookService". Why?

    Slice tests include only the beans of their layer. Dependencies from other layers are replaced with test doubles.
  2. 2. In a @DataJpaTest, one test deletes all rows. What does the next test see?

    @DataJpaTest makes every test transactional and rolls back afterwards, so tests are isolated.
  3. 3. Your suite has 40 test classes using @SpringBootTest, and each one declares a different combination of @MockitoBean fields. What is the likely effect?

    The context cache key includes the bean overrides. Standardizing test configuration lets classes share a context.
  4. 4. Why might a query that passes in a @DataJpaTest with the default embedded H2 database fail in production on PostgreSQL?

    Native SQL, functions and locking differ between engines. Use Replace.NONE plus a Testcontainers PostgreSQL to test the real engine.
  5. 5. Which annotation replaces Spring Boot's @MockBean in current versions?

    @MockitoBean (Spring Framework 6.2+) replaces @MockBean, which was deprecated in Boot 3.4 and removed in Boot 4. @Mock alone creates a mock that is not in the Spring context.

Summary

  • spring-boot-starter-test brings JUnit, Spring Test, AssertJ, Mockito, JsonPath and more.
  • Test most logic with plain unit tests: constructor injection and injected Clocks make services easy to test without Spring.
  • @WebMvcTest + MockMvc (or MockMvcTester) tests the web layer through the real DispatcherServlet without a server; replace services with @MockitoBean.
  • @DataJpaTest tests repositories with a rollback after every test; it uses an embedded database unless you set Replace.NONE.
  • @SpringBootTest starts the full application (MOCK, RANDOM_PORT or NONE); keep these few and focused.
  • Spring caches contexts by configuration; differing mocks, properties and @DirtiesContext multiply startup time.
  • Testcontainers with @ServiceConnection runs tests against the real database engine.

Next: Spring Security protects the API with authentication and authorization, and shows how the security filter chain works.