Chapter 11

Testing

Spring Boot makes it very easy to write slow tests. The skill is choosing the smallest context that can still prove the thing you care about.

⏱ 22 min readLevel: intermediateJUnit 5
Pyramid of Spring Boot test types from full @SpringBootTest with a real server down to plain JUnit unit tests
Most of your tests belong at the bottom. Slices are the useful middle.

What the test starter gives you

one dependency, seven libraries
spring-boot-starter-test
├── JUnit 5 (Jupiter)         the test engine
├── AssertJ                   fluent assertions — prefer over JUnit's
├── Mockito                   mocking
├── Hamcrest                  matchers, used by MockMvc
├── JSONassert                lenient JSON comparison
├── JsonPath                  querying JSON responses
└── spring-test               MockMvc, context caching, @MockitoBean

Level 1: plain unit tests

No Spring. Milliseconds. This should be the majority of your suite — business logic does not need a container to be exercised.

BookServiceTest.java
@ExtendWith(MockitoExtension.class)
class BookServiceTest {

    @Mock  BookRepository repository;
    @Mock  StockClient stockClient;
    @InjectMocks BookService service;

    @Test
    void requireThrowsWhenMissing() {
        when(repository.findById(42L)).thenReturn(Optional.empty());

        assertThatThrownBy(() -> service.require(42L))
                .isInstanceOf(BookNotFoundException.class)
                .hasMessageContaining("42");
    }

    @Test
    void createRejectsDuplicateIsbn() {
        when(repository.existsByIsbn("9781234567897")).thenReturn(true);

        assertThatThrownBy(() -> service.create(command("9781234567897")))
                .isInstanceOf(DuplicateIsbnException.class);

        verify(repository, never()).save(any());
    }

    @Test
    void appliesDiscountToBulkOrders() {
        BigDecimal total = service.priceFor(new BigDecimal("10.00"), 100);
        assertThat(total).isEqualByComparingTo("900.00");   // 10% bulk discount
    }
}
Constructor injection pays off here

You can also write new BookService(mockRepo, mockClient) and skip Mockito's injection entirely. That is a legitimate style and it is only possible because the class takes its dependencies through the constructor — see chapter 3.

Level 2: @WebMvcTest — the web layer only

Loads controllers, JSON converters, validators, filters and exception advice. Does not load @Service or @Repository beans — you supply those as mocks.

BookControllerTest.java
@WebMvcTest(BookController.class)
class BookControllerTest {

    @Autowired MockMvc mvc;
    @Autowired ObjectMapper json;

    @MockitoBean BookService bookService;      // @MockBean is deprecated in Boot 3.4+

    @Test
    void returnsBookAsJson() throws Exception {
        when(bookService.require(1L)).thenReturn(sampleBook());

        mvc.perform(get("/api/books/1"))
           .andExpect(status().isOk())
           .andExpect(content().contentType(MediaType.APPLICATION_JSON))
           .andExpect(jsonPath("$.id").value(1))
           .andExpect(jsonPath("$.title").value("Effective Java"))
           .andExpect(jsonPath("$.internalNote").doesNotExist());   // must not leak
    }

    @Test
    void returns404WithProblemDetail() throws Exception {
        when(bookService.require(99L)).thenThrow(new BookNotFoundException(99L));

        mvc.perform(get("/api/books/99"))
           .andExpect(status().isNotFound())
           .andExpect(content().contentType("application/problem+json"))
           .andExpect(jsonPath("$.detail").value("Book 99 was not found"));
    }

    @Test
    void validatesRequestBody() throws Exception {
        mvc.perform(post("/api/books")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content("""
                                 { "title": "", "authorId": 1, "price": -1 }
                                 """))
           .andExpect(status().isBadRequest())
           .andExpect(jsonPath("$.errors.length()").value(2));

        verifyNoInteractions(bookService);        // never reached the service
    }

    @Test
    void passesPageableThrough() throws Exception {
        mvc.perform(get("/api/books?page=2&size=10&sort=title,desc"))
           .andExpect(status().isOk());

        ArgumentCaptor<Pageable> captor = ArgumentCaptor.forClass(Pageable.class);
        verify(bookService).search(any(), any(), captor.capture());

        assertThat(captor.getValue().getPageNumber()).isEqualTo(2);
        assertThat(captor.getValue().getSort().getOrderFor("title").getDirection())
                .isEqualTo(Sort.Direction.DESC);
    }
}

Level 3: @DataJpaTest — the persistence layer only

Loads entities, repositories and a TestEntityManager. Each test runs in a transaction that is rolled back afterwards.

BookRepositoryTest.java
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)  // use the real DB
class BookRepositoryTest extends AbstractPostgresTest {

    @Autowired BookRepository books;
    @Autowired TestEntityManager em;

    @Test
    void findsByIsbn() {
        Author author = em.persist(new Author("Joshua Bloch"));
        em.persist(new Book("Effective Java", "9780134685991",
                            new BigDecimal("42.00"), author));
        em.flush();
        em.clear();                               // force a real SELECT, not a cache hit

        assertThat(books.findByIsbn("9780134685991"))
                .isPresent()
                .get()
                .extracting(Book::getTitle)
                .isEqualTo("Effective Java");
    }

    @Test
    void enforcesUniqueIsbn() {
        Author author = em.persist(new Author("Someone"));
        em.persist(new Book("First",  "9780134685991", TEN, author));
        em.flush();

        books.save(new Book("Second", "9780134685991", TEN, author));

        assertThatThrownBy(em::flush)
                .isInstanceOf(PersistenceException.class);
    }

    @Test
    void fetchJoinAvoidsNPlusOne() {
        seedBooks(20);
        em.flush();
        em.clear();

        Statistics stats = em.getEntityManager()
                             .getEntityManagerFactory()
                             .unwrap(SessionFactory.class)
                             .getStatistics();
        stats.clear();

        List<Book> result = books.findAllWithAuthor();
        result.forEach(b -> b.getAuthor().getName());   // would trigger N queries if lazy

        assertThat(result).hasSize(20);
        assertThat(stats.getPrepareStatementCount()).isEqualTo(1);
    }
}
@DataJpaTest swaps your database for H2 by default

Convenient and fast, but H2 is not PostgreSQL: different reserved words, no JSONB operators, different upsert syntax, different constraint-violation error codes. Anything vendor-specific must be tested against the real engine — @AutoConfigureTestDatabase(replace = NONE) plus Testcontainers, as above.

Testcontainers

pom.xml
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-testcontainers</artifactId>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.testcontainers</groupId>
  <artifactId>postgresql</artifactId>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.testcontainers</groupId>
  <artifactId>junit-jupiter</artifactId>
  <scope>test</scope>
</dependency>
AbstractPostgresTest.java — the modern @ServiceConnection style
@Testcontainers
public abstract class AbstractPostgresTest {

    @Container
    @ServiceConnection                       // Boot 3.1+: wires the DataSource automatically
    static final PostgreSQLContainer<?> POSTGRES =
            new PostgreSQLContainer<>("postgres:16-alpine")
                    .withReuse(true);
}

@ServiceConnection removes the @DynamicPropertySource boilerplate entirely — it knows how to configure Spring for Postgres, Redis, Kafka, MongoDB, RabbitMQ and more.

TestBookstoreApplication.java — containers for local development too
public class TestBookstoreApplication {

    public static void main(String[] args) {
        SpringApplication.from(BookstoreApplication::main)
                .with(ContainerConfig.class)
                .run(args);
    }

    @TestConfiguration(proxyBeanMethods = false)
    static class ContainerConfig {

        @Bean
        @ServiceConnection
        PostgreSQLContainer<?> postgres() {
            return new PostgreSQLContainer<>("postgres:16-alpine");
        }

        @Bean
        @ServiceConnection(name = "redis")
        GenericContainer<?> redis() {
            return new GenericContainer<>("redis:7-alpine").withExposedPorts(6379);
        }
    }
}

Run that class and your whole dependency stack starts in Docker. No local Postgres install, no docker-compose up to remember.

Level 4: @SpringBootTest

BookApiIT.java
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
@ActiveProfiles("test")
class BookApiIT extends AbstractPostgresTest {

    @Autowired TestRestTemplate rest;
    @Autowired BookRepository books;

    @Test
    void createThenFetch() {
        BookRequest request = new BookRequest("Clean Code", 1L, new BigDecimal("35.00"), Set.of());

        ResponseEntity<BookResponse> created =
                rest.postForEntity("/api/books", request, BookResponse.class);

        assertThat(created.getStatusCode()).isEqualTo(HttpStatus.CREATED);
        assertThat(created.getHeaders().getLocation()).isNotNull();

        ResponseEntity<BookResponse> fetched =
                rest.getForEntity(created.getHeaders().getLocation(), BookResponse.class);

        assertThat(fetched.getBody().title()).isEqualTo("Clean Code");
        assertThat(books.count()).isEqualTo(1);
    }
}
webEnvironmentBehaviourClient
MOCK (default)Mock servlet environment, no socketMockMvc
RANDOM_PORTReal server on a free portTestRestTemplate, WebTestClient
DEFINED_PORTReal server on the configured portSame — avoid, it causes CI conflicts
NONENo web environment at all—

Context caching — the thing that decides your build time

Spring caches an ApplicationContext and reuses it across test classes with an identical configuration. Change anything in that configuration and you get a brand-new context, costing seconds each time.

what makes a context unique
· the set of configuration classes
· active profiles
· @TestPropertySource / properties = {...} values
· which beans are replaced by @MockitoBean       ← the usual culprit
· context initializers
· the web environment type
The slow-suite anti-pattern

Twenty @SpringBootTest classes, each mocking a slightly different bean, gives you twenty full contexts. A three-minute suite becomes twenty. Standardise: put the shared configuration on one abstract base class, use identical property sets, and prefer slices over full contexts.

@SpringBootTest
@ActiveProfiles("test")
@AutoConfigureMockMvc
public abstract class AbstractIntegrationTest extends AbstractPostgresTest {
    @Autowired protected MockMvc mvc;
    @Autowired protected ObjectMapper json;
}
// every integration test extends this → ONE cached context
measure it
logging:
  level:
    org.springframework.test.context.cache: DEBUG
# logs: "Spring test ApplicationContext cache statistics: size = 7, hitCount = 42, missCount = 7"

Test data

three approaches
/* 1 · @Sql scripts — explicit, readable diffs */
@Sql(scripts = "/fixtures/books.sql")
@Sql(scripts = "/fixtures/clean.sql", executionPhase = AFTER_TEST_METHOD)
class BookQueryTest { }

/* 2 · object mothers — type-safe, refactor-friendly */
public final class Books {

    public static Book.Builder aBook() {
        return Book.builder()
                   .title("Effective Java")
                   .isbn(randomIsbn())
                   .price(new BigDecimal("42.00"))
                   .status(BookStatus.PUBLISHED);
    }

    public static Book anOutOfPrintBook() {
        return aBook().status(BookStatus.OUT_OF_PRINT).build();
    }
}

/* 3 · @Transactional rollback — the default in @DataJpaTest */
@Test
@Transactional
void changesAreRolledBackAfterThisTest() { }
@Transactional on an integration test can lie to you

The test method and the code under test share one transaction, so nothing is ever really committed. That hides constraint violations that only fire at commit, and it hides missing @Transactional on your service — the test's transaction covers for it. For true end-to-end tests, commit for real and clean up explicitly.

Mocking external HTTP services

WireMock via Testcontainers
@SpringBootTest
class InventoryClientIT {

    @Container
    static WireMockContainer wiremock = new WireMockContainer("wiremock/wiremock:3.9.1");

    @DynamicPropertySource
    static void props(DynamicPropertyRegistry registry) {
        registry.add("bookstore.inventory.base-url", wiremock::getBaseUrl);
    }

    @Autowired InventoryClient client;

    @Test
    void parsesStockResponse() {
        wiremock.getClient().register(get(urlEqualTo("/stock/9780134685991"))
                .willReturn(okJson("""
                        { "isbn": "9780134685991", "available": 12 }
                        """)));

        assertThat(client.stockFor("9780134685991").available()).isEqualTo(12);
    }

    @Test
    void failsFastOnTimeout() {
        wiremock.getClient().register(get(anyUrl())
                .willReturn(aResponse().withFixedDelay(10_000)));

        assertThatThrownBy(() -> client.stockFor("x"))
                .isInstanceOf(ResourceAccessException.class);
    }
}

A test strategy that scales

What you are testingUseRoughly
Business rules, calculations, edge casesPlain JUnit + Mockito70% of tests
Request/response contract, validation, status codes@WebMvcTest15%
Queries, mappings, constraints, N+1@DataJpaTest + Testcontainers10%
Critical end-to-end flows@SpringBootTest5%

Checklist

  • Business logic tested without Spring.
  • Slices preferred over @SpringBootTest.
  • One shared base class per context shape, to keep the cache hitting.
  • Vendor-specific SQL tested on the real engine.
  • Query counts asserted on list endpoints.
  • Security tested for anonymous, wrong role and correct role.
  • External HTTP stubbed, with a timeout test.
  • The same migrations run in tests as in production.

Your suite has 25 @SpringBootTest classes and takes 12 minutes. What is the most likely cause?

Each unique combination of profiles, properties and @MockitoBean declarations produces its own ApplicationContext. Twenty-five variations means twenty-five full startups. Standardising on one base class usually cuts such a suite by 70–80%.