Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/spring-projects/spring-boot/llms.txt

Use this file to discover all available pages before exploring further.

Spring Boot provides @SpringBootTest for full application-context integration tests and a family of focused @...Test slice annotations for testing individual layers in isolation. Choosing the right approach keeps tests fast—slice tests start in milliseconds because they only load the beans relevant to a particular part of the application, while @SpringBootTest is reserved for end-to-end scenarios that need the full context.

@SpringBootTest web environment modes

@SpringBootTest creates an ApplicationContext through SpringApplication. Its webEnvironment attribute controls whether an embedded server is started and how it is configured.
Loads a web ApplicationContext with a mock web environment. No embedded server starts. Use with @AutoConfigureMockMvc or @AutoConfigureWebTestClient for mock-based web testing.
@SpringBootTest
@AutoConfigureMockMvc
@AutoConfigureRestTestClient
@AutoConfigureWebTestClient
class MyMockMvcTests {

    @Test
    void testWithMockMvc(@Autowired MockMvc mvc) throws Exception {
        mvc.perform(get("/"))
                .andExpect(status().isOk())
                .andExpect(content().string("Hello World"));
    }

    @Test
    void testWithMockMvcTester(@Autowired MockMvcTester mvc) {
        assertThat(mvc.get().uri("/"))
                .hasStatusOk()
                .hasBodyTextEqualTo("Hello World");
    }

    @Test
    void testWithRestTestClient(@Autowired RestTestClient restClient) {
        restClient
                .get().uri("/")
                .exchange()
                .expectStatus().isOk()
                .expectBody(String.class).isEqualTo("Hello World");
    }

    @Test
    void testWithWebTestClient(@Autowired WebTestClient webClient) {
        webClient
                .get().uri("/")
                .exchange()
                .expectStatus().isOk()
                .expectBody(String.class).isEqualTo("Hello World");
    }

}
Testing within a mocked environment is typically faster than starting a real servlet container. However, Spring Boot’s error handling depends on servlet container “error page” support, so custom error pages cannot be directly tested with MockMvc alone.
If your test is @Transactional, the transaction rolls back at the end of each test method by default. With RANDOM_PORT or DEFINED_PORT, the HTTP client and server run in separate threads and therefore in separate transactions, so server-side transactions do not roll back automatically.

Slice tests

Each slice annotation loads a narrowly scoped ApplicationContext and restricts component scanning to the beans relevant to that layer. Beans that do not belong to the slice (such as @Component classes in a @WebMvcTest) are excluded, and collaborators are typically provided as @MockitoBean mocks.

@WebMvcTest — Spring MVC layer

@WebMvcTest auto-configures the Spring MVC infrastructure and limits scanned beans to controllers, ControllerAdvice, converters, filters, interceptors, and WebMvcConfigurer implementations. Regular @Component beans are not scanned. The slice also auto-configures MockMvc and MockMvcTester.
@WebMvcTest(UserVehicleController.class)
class MyControllerTests {

    @Autowired
    private MockMvcTester mvc;

    @MockitoBean
    private UserVehicleService userVehicleService;

    @Test
    void testExample() {
        given(this.userVehicleService.getVehicleDetails("sboot"))
            .willReturn(new VehicleDetails("Honda", "Civic"));
        assertThat(this.mvc.get().uri("/sboot/vehicle").accept(MediaType.TEXT_PLAIN))
            .hasStatusOk()
            .hasBodyTextEqualTo("Honda Civic");
    }

}
You can also auto-configure MockMvc and MockMvcTester in a full @SpringBootTest by adding @AutoConfigureMockMvc. This gives you the MVC testing API without restricting the application context to a slice.

@DataJpaTest — JPA persistence layer

@DataJpaTest scans for @Entity classes and configures Spring Data JPA repositories. If an in-memory embedded database is available on the classpath, it is configured automatically. SQL queries are logged by default. Tests are transactional and roll back after each method.
@DataJpaTest
class MyRepositoryTests {

    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private UserRepository repository;

    @Test
    void testExample() {
        this.entityManager.persist(new User("sboot", "1234"));
        User user = this.repository.findByUsername("sboot");
        assertThat(user.getUsername()).isEqualTo("sboot");
        assertThat(user.getEmployeeNumber()).isEqualTo("1234");
    }

}
TestEntityManager is an alternative to the standard JPA EntityManager designed for use in tests. It is also available in non-@DataJpaTest tests via @AutoConfigureTestEntityManager.

@DataMongoTest — MongoDB persistence layer

@DataMongoTest configures a MongoTemplate, scans for @Document classes, and sets up Spring Data MongoDB repositories. Regular @Component and @ConfigurationProperties beans are not scanned.

@WebFluxTest — Spring WebFlux layer

@WebFluxTest auto-configures the Spring WebFlux infrastructure and limits scanned beans to controllers, ControllerAdvice, converters, and WebFluxConfigurer implementations. It also auto-configures WebTestClient.
@WebFluxTest(UserVehicleController.class)
class MyControllerTests {

    @Autowired
    private WebTestClient webClient;

    @MockitoBean
    private UserVehicleService userVehicleService;

    @Test
    void testExample() {
        given(this.userVehicleService.getVehicleDetails("sboot"))
            .willReturn(new VehicleDetails("Honda", "Civic"));
        this.webClient.get().uri("/sboot/vehicle").accept(MediaType.TEXT_PLAIN).exchange()
            .expectStatus().isOk()
            .expectBody(String.class).isEqualTo("Honda Civic");
    }

}
@WebFluxTest cannot detect routes registered through the functional web framework. For testing RouterFunction beans, import them with @Import or use a full @SpringBootTest.

@JsonTest — JSON serialization

@JsonTest auto-configures the available JSON mapper (Jackson, Gson, or Jsonb) and provides JacksonTester, GsonTester, JsonbTester, and BasicJsonTester helpers for asserting on serialized and deserialized JSON.
@JsonTest
class MyJsonTests {

    @Autowired
    private JacksonTester<VehicleDetails> json;

    @Test
    void serialize() throws Exception {
        VehicleDetails details = new VehicleDetails("Honda", "Civic");
        assertThat(this.json.write(details)).isEqualToJson("expected.json");
        assertThat(this.json.write(details)).hasJsonPathStringValue("@.make");
        assertThat(this.json.write(details)).extractingJsonPathStringValue("@.make").isEqualTo("Honda");
    }

    @Test
    void deserialize() throws Exception {
        String content = "{\"make\":\"Ford\",\"model\":\"Focus\"}";
        assertThat(this.json.parse(content)).isEqualTo(new VehicleDetails("Ford", "Focus"));
        assertThat(this.json.parseObject(content).getMake()).isEqualTo("Ford");
    }

}

@RestClientTest — REST client testing

@RestClientTest auto-configures Jackson, GSON, and Jsonb support, a RestTemplateBuilder, a RestClient.Builder, and a MockRestServiceServer. Use the value or components attribute to specify which beans under test to load.

Available test modules

Spring Boot ships dedicated -test modules for each major technology area. Each module provides focused slice annotations:
ModuleAnnotation
spring-boot-webmvc-test@WebMvcTest
spring-boot-webflux-test@WebFluxTest
spring-boot-restclient-test@RestClientTest
spring-boot-webclient-test@WebClientTest
spring-boot-graphql-test@GraphQlTest
ModuleAnnotation
spring-boot-data-jpa-test@DataJpaTest
spring-boot-data-jdbc-test@DataJdbcTest
spring-boot-jdbc-test@JdbcTest
spring-boot-mongodb-test@DataMongoTest
spring-boot-data-r2dbc-test@DataR2dbcTest
spring-boot-data-redis-test@DataRedisTest
spring-boot-data-cassandra-test@DataCassandraTest
spring-boot-data-couchbase-test@DataCouchbaseTest
spring-boot-data-elasticsearch-test@DataElasticsearchTest
spring-boot-data-neo4j-test@DataNeo4jTest
spring-boot-jooq-test@JooqTest
ModuleAnnotation
spring-boot-test-autoconfigure@JsonTest
spring-boot-micrometer-metrics-testmetrics support
spring-boot-micrometer-tracing-testtracing support
spring-boot-webservices-test@WebServiceClientTest, @WebServiceServerTest
You can combine @AutoConfigure... annotations from multiple slices with a standard @SpringBootTest when you need auto-configured test beans without slicing the application.

Build docs developers (and LLMs) love