Database / Liquibase interview questions
How do you use Liquibase with Docker and Testcontainers in integration tests?
Testcontainers is a Java library that spins up real Docker containers during JUnit tests, providing actual database instances instead of in-memory databases. Combining Testcontainers with Liquibase gives you integration tests that run against a realistic database — same engine type, same version — with an auto-migrated schema, without any manual database setup.
Maven dependency:
<dependency> <groupId>org.testcontainers</groupId> <artifactId>postgresql</artifactId> <version>1.19.3</version> <scope>test</scope> </dependency>
JUnit 5 test with Spring Boot and Testcontainers:
@SpringBootTest @Testcontainers class OrderRepositoryIntegrationTest { @Container static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16") .withDatabaseName("testdb") .withUsername("test") .withPassword("test"); @DynamicPropertySource static void postgresProperties(DynamicPropertyRegistry registry) { registry.add("spring.datasource.url", postgres::getJdbcUrl); registry.add("spring.datasource.username", postgres::getUsername); registry.add("spring.datasource.password", postgres::getPassword); } // Spring Boot auto-runs Liquibase on startup using the dynamic datasource URL // By the time @Test methods run, all changeSets are applied @Autowired OrderRepository orderRepository; @Test void shouldSaveAndRetrieveOrder() { Order order = new Order("customer-1", BigDecimal.valueOf(99.99)); orderRepository.save(order); assertThat(orderRepository.findById(order.getId())).isPresent(); } }
When Spring Boot starts with the dynamic Testcontainers URL, it auto-runs Liquibase migrations before the test context is ready. By the time @Test methods execute, the schema is fully migrated. The container is stopped and removed after the test class completes.
More Related questions...