Skip to content
Spring Boot sb testing 3 min read

@SpringBootTest

@SpringBootTest boots the entire application context for a test — every bean, every auto-configuration, exactly as the real app starts. Use it when the interaction between layers is what you want to verify, not a single class in isolation. For narrower, faster tests prefer a test slice like @WebMvcTest or @DataJpaTest.

A full-context test

@SpringBootTest searches up the package tree for your @SpringBootApplication class and uses it to build the context. You can then @Autowired any bean.

@SpringBootTest
class OrderServiceIntegrationTest {

    @Autowired
    OrderService service;

    @Test
    void placesAndPersistsOrder() {
        Order saved = service.place("alice");
        assertThat(saved.getId()).isNotNull();
    }
}

Because the full context starts, this is slower than a unit test — but Spring caches the context and reuses it across test classes with the same configuration, so the cost is paid once.

webEnvironment options

The webEnvironment attribute controls whether (and how) a servlet environment starts.

ValueBehavior
MOCK (default)Loads a web context with a mock servlet environment; no real port. Pair with MockMvc.
RANDOM_PORTStarts the embedded server on a random free port. Real HTTP.
DEFINED_PORTStarts on the configured server.port.
NONENo web environment at all (for non-web apps).
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class ApiIntegrationTest {

    @Autowired
    TestRestTemplate restTemplate;        // auto-configured for RANDOM/DEFINED_PORT

    @LocalServerPort
    int port;                             // the actual port chosen
}

Note: TestRestTemplate and WebTestClient are auto-configured only for RANDOM_PORT and DEFINED_PORT. With MOCK (the default) you use MockMvc instead. See Integration Testing for full RANDOM_PORT examples.

Calling the running app with TestRestTemplate

TestRestTemplate is a fault-tolerant wrapper around RestTemplate made for tests — it does not throw on 4xx/5xx, so you can assert on error responses.

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class ProductApiTest {

    @Autowired TestRestTemplate rest;

    @Test
    void createsProduct() {
        var body = new ProductRequest("Keyboard", new BigDecimal("49.90"));

        ResponseEntity<Product> response =
                rest.postForEntity("/api/products", body, Product.class);

        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED);
        assertThat(response.getBody().name()).isEqualTo("Keyboard");
    }
}

For a fluent, assertion-oriented client (also usable for MVC apps) reach for WebTestClient:

webTestClient.get().uri("/api/products/1")
        .exchange()
        .expectStatus().isOk()
        .expectBody().jsonPath("$.name").isEqualTo("Keyboard");

Overriding beans with @TestConfiguration

When a test needs a different bean — say a fake clock or a stubbed external client — declare a @TestConfiguration. Unlike @Configuration, it is not picked up by component scanning; you opt in by importing it, so it only affects tests that ask for it.

@SpringBootTest
@Import(OrderServiceIntegrationTest.TestBeans.class)
class OrderServiceIntegrationTest {

    @TestConfiguration
    static class TestBeans {
        @Bean
        Clock fixedClock() {
            return Clock.fixed(Instant.parse("2026-06-13T10:00:00Z"), ZoneOffset.UTC);
        }
    }
}

To replace a bean with a mock instead, use @MockitoBean — the field becomes a Mockito mock registered in the context, replacing the real bean.

@MockitoBean
PaymentGateway paymentGateway;   // real bean swapped for a mock

Selecting configuration and profiles

Activate a profile so test-specific properties (application-test.yml) and profile-scoped beans apply.

@SpringBootTest
@ActiveProfiles("test")
class WithTestProfile { }

You can also override individual properties inline, which is cleaner than a whole profile for one-off needs:

@SpringBootTest(properties = {
    "spring.datasource.url=jdbc:h2:mem:testdb",
    "app.feature.new-checkout=true"
})
class WithInlineProps { }

Context caching and @DirtiesContext

Spring caches and reuses the context across test classes that share the same configuration — the single biggest test-speed lever. A test that mutates shared state (singleton beans, static caches) can leak into later tests. @DirtiesContext tells Spring to discard and rebuild the context.

@SpringBootTest
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
class MutatesSharedStateTest { }

Warning: @DirtiesContext is expensive — it throws away the cached context and rebuilds it. Use it only when state truly leaks. Most of the time, resetting state in @BeforeEach or wrapping tests in @Transactional (which rolls back) is far cheaper.

AnnotationPurpose
@SpringBootTestBoot the full application context
@ActiveProfilesActivate Spring profiles for the test
@TestConfigurationAdd/override beans for tests, imported explicitly
@MockitoBeanReplace a context bean with a Mockito mock
@DirtiesContextDiscard the cached context after the test
Last updated June 13, 2026
Was this helpful?