Testing Spring Boot apps
Spring Boot has first-class testing support. You can test one layer in isolation in milliseconds (test slices), or start the whole application with a real database. A good test suite uses both: many fast, focused tests and a few end-to-end ones. Everything here uses JUnit, AssertJ and Mockito, which the test starters include.
Three kinds of tests
| Annotation | Loads | Speed | Use for |
|---|---|---|---|
| (none: plain JUnit) | Nothing | Fastest | Services and domain logic, with fakes or mocks |
@WebMvcTest |
Controllers, advice, JSON, validation | Fast | HTTP behaviour: status codes, JSON, validation |
@DataJpaTest |
Entities, repositories, an in-memory database | Fast | Queries and mappings |
@SpringBootTest |
The whole application | Slowest | End-to-end checks of important flows |
In Spring Boot 4, each slice lives in its technology's test starter (spring-boot-starter-webmvc-test, spring-boot-starter-data-jpa-test).
Testing the web layer
@WebMvcTest starts only the web layer: no database, no services. Dependencies of the controller are replaced with Mockito mocks via @MockitoBean, and requests go through MockMvcTester, which uses AssertJ-style assertions:
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import java.math.BigDecimal;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.assertj.MockMvcTester;
@WebMvcTest(ProductController.class) // only the web layer: controller + advice, no database
class ProductControllerTest {
@Autowired
MockMvcTester mvc;
@MockitoBean
ProductService service;
@Test
void returnsAProduct() {
given(service.findById(2L)).willReturn(new Product("Mug", new BigDecimal("8.99"), 200, "kitchen"));
assertThat(mvc.get().uri("/api/products/2"))
.hasStatusOk()
.bodyJson()
.extractingPath("$.name").isEqualTo("Mug");
}
@Test
void unknownProductIs404ProblemDetail() {
given(service.findById(99L)).willThrow(new ProductNotFoundException(99L));
assertThat(mvc.get().uri("/api/products/99"))
.hasStatus(404)
.hasContentType(MediaType.APPLICATION_PROBLEM_JSON)
.bodyJson()
.extractingPath("$.detail").isEqualTo("Product 99 does not exist");
}
@Test
void rejectsInvalidProduct() {
assertThat(mvc.post().uri("/api/products")
.contentType(MediaType.APPLICATION_JSON)
.content("""
{"name": "", "price": 0, "stock": 1, "category": "kitchen"}
"""))
.hasStatus(400)
.bodyJson()
.extractingPath("$.errors[*].field").asArray().containsExactly("name", "price");
verify(service, never()).create(any());
}
}The last test checks two things: the response lists exactly the invalid fields, and the service was never called, proving validation happens before any business logic runs.
Testing repositories
@DataJpaTest configures JPA with an embedded database. Each test runs in a transaction that's rolled back afterwards, so tests don't affect each other:
@DataJpaTest
class ProductRepositoryTest {
@Autowired
ProductRepository products;
@Test
void findsByCategoryCheapestFirst() {
products.save(new Product("Kettle", new BigDecimal("45.00"), 3, "kitchen"));
products.save(new Product("Spoon", new BigDecimal("2.50"), 0, "kitchen"));
products.save(new Product("Desk", new BigDecimal("150.00"), 1, "office"));
assertThat(products.findByCategoryOrderByPriceAsc("kitchen"))
.extracting(Product::getName)
.containsExactly("Spoon", "Kettle");
assertThat(products.findSoldOut()).extracting(Product::getName).containsExactly("Spoon");
}
}For queries that use database-specific features, test against the real database engine with Testcontainers, which starts PostgreSQL in Docker for the test run:
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.postgresql.PostgreSQLContainer; // Testcontainers 2 (artifact testcontainers-postgresql)
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Testcontainers
class ProductRepositoryPostgresTest {
@Container
@ServiceConnection // Spring Boot points the datasource at the container
static PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:18");
…
}Testing the whole application
@SpringBootTest starts the complete application. Combined with @AutoConfigureMockMvc it's still fast, because no real server is started:
@SpringBootTest
@AutoConfigureMockMvc
class ShopApplicationTests {
@Autowired
MockMvcTester mvc;
@Test
void listsTheSeededProducts() {
assertThat(mvc.get().uri("/api/products?category=kitchen"))
.hasStatusOk()
.bodyJson()
.extractingPath("$[*].name").asArray().containsExactly("Mug", "Teapot");
}
@Test
void calculatesPriceWithTax() {
assertThat(mvc.get().uri("/api/price?net=100"))
.hasStatusOk()
.bodyJson()
.extractingPath("$.gross").isEqualTo("118.00 INR");
}
}Use @SpringBootTest(webEnvironment = RANDOM_PORT) when you want a real server on a random port, for example to test HTTP clients.
Running the tests
./mvnw test[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 -- in com.example.shop.product.ProductRepositoryTest [INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0 -- in com.example.shop.product.ProductControllerTest [INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0 -- in com.example.shop.ShopApplicationTests [INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0 [INFO] BUILD SUCCESS
Spring caches application contexts between test classes with the same configuration, so a suite with many @SpringBootTest classes starts the application only once, as long as you don't give each class a different set of mocks or properties.
A lesson learned while writing these tests
The first run of these exact tests failed. @WebMvcTest reported "No qualifying bean of type 'ProductRepository' available", and the repository test found extra products. The cause: sample data was created by a @Bean CommandLineRunner method on the main application class. Slices always load the main class's @Bean methods, so the web slice tried to build it without a repository, and the JPA slice ran it and inserted the sample rows. Moving the seeding into its own @Component (which slices skip) fixed both. Keep the main application class empty.
Practice
- Add a
@WebMvcTesttest forDELETE /api/products/1that checks the 204 status and thatservice.delete(1L)was called. - Add a repository test for
findByNameContainingIgnoreCase("MU"). - Write a plain JUnit test for
PriceCalculatorby constructing it withnew PricingProperties(...): no Spring needed.
1.What does @WebMvcTest(ProductController.class) start?
2.What happens to data saved in a @DataJpaTest test?
3.What is @MockitoBean for?