DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Join us today at 1 PM EST: "3-Step Approach to Comprehensive Runtime Application Security"
Save your seat
  1. DZone
  2. Coding
  3. Frameworks
  4. DAO Integration Test With TestContainers, Spring Boot, Liquibase, and PostgresSQL

DAO Integration Test With TestContainers, Spring Boot, Liquibase, and PostgresSQL

In this article, we will cover how to do a DAO integration test when you have a spring boot application with PostgreSQL DB and Liquibase for schema versioning.

Mahmoud Romeh user avatar by
Mahmoud Romeh
·
Mar. 12, 19 · Tutorial
Like (2)
Save
Tweet
Share
24.86K Views

Join the DZone community and get the full member experience.

Join For Free

Image title

In this article, we will cover how to do a DAO integration test when you have a spring boot application with PostgreSQL DB and Liquibase for schema versioning. Last time, we explained how to do the same without Liquibase using embedded PostgreSQL, but this time, we will do the same but use Docker with test containers, which will apply your Liquibase changes and make sure your DAO integration test has the same environment as the production database environment if you are using Docker for your database in production.

The whole code example is on GitHub.

Maven Dependencies

Beside spring boot starter dependencies, we will need to add Liquibase and test containers dependencies. The whole maven pom file can be viewed in the GitHub code.

 <dependency>
            <groupId>org.liquibase</groupId>
            <artifactId>liquibase-maven-plugin</artifactId>
            <version>3.6.3</version>
 </dependency>
<dependency>
            <groupId>org.testcontainers</groupId>
            <artifactId>postgresql</artifactId>
            <version>1.10.5</version>
</dependency>

Your Liquibase database simple master configuration will be in your resources source set, which will create a simple customer table with the file name changelog-master.xml.

Spring Boot DAO Integration Test Configuration

We will highlight the important sections. The whole Java file configuration can be viewed here: DbConfig.java

Data source configuration for test:

@Bean
public DataSource dataSource() {
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("org.postgresql.Driver");
    // here we reference the static test container variable in our test case to get the used the connection details
ds.setUrl(format("jdbc:postgresql://%s:%s/%s", postgreSQLContainer.getContainerIpAddress(),
postgreSQLContainer.getMappedPort(
PostgreSQLContainer.POSTGRESQL_PORT), postgreSQLContainer.getDatabaseName()));
ds.setUsername(postgreSQLContainer.getUsername());
ds.setPassword(postgreSQLContainer.getPassword());
ds.setSchema(postgreSQLContainer.getDatabaseName());
return ds;
}

Spring Liquibase configuration for test:

@Bean
public SpringLiquibase springLiquibase(DataSource dataSource) throws SQLException {
    // here we create the schema first if not yet created before 
tryToCreateSchema(dataSource);
SpringLiquibase liquibase = new SpringLiquibase();
    // we want to drop the datasbe if it was created before to have immutable version
liquibase.setDropFirst(true);
liquibase.setDataSource(dataSource);
    //you set the schema name which will be used into ur integration test
liquibase.setDefaultSchema("test");
    // the classpath reference for your liquibase changlog 
liquibase.setChangeLog("classpath:/db/changelog/changelog-master.xml");
return liquibase;
}

Do not forget to disable the hibernate DDL generation in hibernate properties, as you can see in the Dbconfig:

ps.put("hibernate.hbm2ddl.auto", "none");

We use Liquibase for our schema definition and versioning.

Now how can we trigger the DAO integration test and use that configuration in practice?

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {DbConfig.class})
@ActiveProfiles("DaoTest")
@Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = "classpath:dao/TestData.sql")
public class PostgresEmbeddedDaoTestingApplicationTests {
  /* Here we have a static postgreSQL test container Class rule to make the instance used 
  for all test methods in the same test class , and we use @Transactional to avoid any dirty data changes between
  different test methods , where we pass our test database configuration ,
  ideally that should be loaded from external config file */
@ClassRule
public static PostgreSQLContainer postgreSQLContainer = (PostgreSQLContainer) new PostgreSQLContainer(
"postgres:10.3")
.withDatabaseName("test")
.withUsername("user")
.withPassword("pass").withStartupTimeout(Duration.ofSeconds(600));

@Autowired
private CustomerRepository customerRepository;

@Test
@Transactional
public void contextLoads() {

customerRepository.save(Customer.builder()
.id(new Random().nextInt())
.address("brussels")
.name("TestName")
.build());

Assert.assertTrue(customerRepository.findCustomerByName("TestName") != null);
}
}

When you run the test from your IDEA, you should see that the Spring Boot application is started properly, and the docker image of the PostgreSQL is started with Liquibase changes applied so you can trigger your DAO integration test in a production-like situation.

The PostgreSQL docker image starts off-course. You need Docker kernel installed on your machine to be able to test the same:

The docker image start for PostgreSQL test container

Liquibase changes are being applied, as you can see in the console logs:

Liquibase changes being applied for the customer table

References

  • TestContainers: https://www.testcontainers.org/
  • Liquibase: https://www.Liquibase.org/
  • Spring Boot: https://spring.io/projects/spring-boot
Spring Framework Decentralized autonomous organization integration test Liquibase Spring Boot

Published at DZone with permission of Mahmoud Romeh, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Project Hygiene
  • Top 5 Node.js REST API Frameworks
  • The 31 Flavors of Data Lineage and Why Vanilla Doesn’t Cut It
  • Best Practices for Writing Clean and Maintainable Code

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: