Cheatsheet

Testing with Spring Boot

Key idea

Spring Boot adds two tools on top of the TestContext: `@SpringBootTest` loads the whole application (finding your `@SpringBootApplication`), and *test slices* (`@WebMvcTest`, `@DataJpaTest`, `@JdbcTest`, `@JsonTest`, `@RestClientTest`…) load just one layer. `@MockitoBean` replaces a context bean with a Mockito mock.

Diagram (UML)

Test ApplicationContextJUnit 5MockMvcMembershipControllerMembershipService@MockitoBean gateway

Key pieces

  • @SpringBootTest(webEnvironment = MOCK | RANDOM_PORT | DEFINED_PORT | NONE)
  • @AutoConfigureMockMvc + MockMvc; TestRestTemplate/RestTestClient + @LocalServerPort for a real server
  • Slices: @WebMvcTest(Controller.class), @DataJpaTest, @JdbcTest, @JsonTest, @RestClientTest
  • @MockitoBean and @MockitoSpyBean (Spring Framework 6.2+); formerly @MockBean/@SpyBean
  • @TestConfiguration: extra beans for tests, not picked up by scanning
  • spring-boot-starter-test: JUnit 5, AssertJ, Hamcrest, Mockito, JSONassert, JsonPath, Spring Test

MockMvcFullContextTest.java

@SpringBootTest                 // the whole application context (finds @SpringBootApplication)…
@AutoConfigureMockMvc           // …plus MockMvc: no real server (webEnvironment = MOCK, the default)
class MockMvcFullContextTest {
    @Autowired
    MockMvc mvc;

    @MockitoBean                // replaces ONLY the bank gateway; the service and controller are real
    PaymentGateway payments;

    @Test
    void renewsThroughTheRealServiceWithAMockedBank() throws Exception {
        given(payments.charge(eq("Ana"), any())).willReturn(true);

        mvc.perform(post("/api/memberships/Ana/renew"))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.plan").value("monthly"));
    }
}

Remember for the exam

  • @SpringBootTest searches upwards for the @SpringBootConfiguration class and starts the full context with auto-configuration
  • The default webEnvironment is MOCK: a web context but no server; you test with MockMvc
  • RANDOM_PORT starts a real server on a free port; you read it with @LocalServerPort
  • @WebMvcTest loads controllers, @ControllerAdvice, converters, filters and MockMvc, but not @Service or @Repository
  • @MockitoBean adds or replaces a bean with a mock; it's reset after each test
  • Slices and @SpringBootTest are cached too; each different @MockitoBean changes the cache key

Exam traps

  • In a @WebMvcTest, if the controller needs a service and you don't mock it, the context doesn't start (NoSuchBeanDefinitionException)
  • @MockBean is deprecated since Boot 3.4 and removed in Boot 4: the equivalent is @MockitoBean (package org.springframework.test.context.bean.override.mockito)
  • With MockMvc there's no server or network: testing ports, TLS or container filters needs RANDOM_PORT
  • A @SpringBootTest with RANDOM_PORT and @Transactional does not roll back what the server does (it runs on another thread)
  • A nested @TestConfiguration is detected on its own; a top-level one must be imported with @Import

← Testing with Spring Boot · Run it