Spring Boot · Lesson 14 of 15
Tests with Testcontainers
Slice tests, MockMvc and a real Postgres in Docker for integration tests.
- Advanced
- 16 min read
- 3 objectives
Before this lessonLesson 13: Domain Events and Messaging
What you will learn
- Write a @WebMvcTest
- Start Postgres in a test
- Replace a bean
Your Progress
0 of 15 lessons 0%
- Lessons0 / 15
- Completed0
- Est. time left~ 4 hours
Create a free account to keep your progress on every device.
Slice tests are fast. Integration tests against a real Postgres in Docker catch the SQL the H2 database hides.
WebMvcTest
@WebMvcTest(TaskController.class)
class TaskControllerTest {
@Autowired MockMvc mvc;
@MockBean TaskService tasks;
@Test
void listsTasks() throws Exception {
when(tasks.list()).thenReturn(List.of(new TaskDto(1L, "Hi", false)));
mvc.perform(get("/api/tasks"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].title").value("Hi"));
}
}Testcontainers
@SpringBootTest
@Testcontainers
class TaskRepoIT {
@Container
static PostgreSQLContainer<?> pg = new PostgreSQLContainer<>("postgres:16-alpine");
@DynamicPropertySource
static void props(DynamicPropertyRegistry r) {
r.add("spring.datasource.url", pg::getJdbcUrl);
r.add("spring.datasource.username", pg::getUsername);
r.add("spring.datasource.password", pg::getPassword);
}
}