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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
