Easy Integration Testing With Testcontainers

In this post, we will take a look at how we can use Testcontainers for our integration tests. Testcontainers will allow us to write integration tests making use of containerized databases, message queues, web browsers, etc. without a dependency on a local installation.


1. Introduction

A common problem when writing integration tests, is the dependency on installed components where the integration tests are supposed to run. Think about databases, message queues, web browsers, etc. Wouldn’t it be great when we could spin off a database instance in a Docker container when starting our integration test? We would always start with a clean database and our integration tests could run on any machine. This is where Testcontainers are designed for. Testcontainers is a Java library which can be used in JUnit tests.

In the next sections, we will create an integration test which is dependent on a PostgreSQL database. We will use the small CRUD Spring Boot application from our previous post. In short, the application is able to add an employee and to retrieve a list of all employees by means of a REST interface. The data is being stored in a PostgreSQL database.

The source code in this post is available at GitHub in branch feature/testcontainers.

2. Create Integration Test

First thing to do is to create an integration test. We will do so for retrieving the list of employees. In a real application it is advised to separate your unit tests from your integration tests. We are not going to explore this in depth in this post, but we will use Spring profiles in order to be able to run our tests when a specific profile is used. If you want to separate unit tests from integration tests, you can simply create and use different profiles based on this example.

In our integration test, we call the getAllEmployees URL, check the HTTP response status and check the content which is retrieved. Remember that we used Liquibase for creating and migrating the database and that we inserted one employee in the database when the Spring profile test is being used.

Java
 




x
21


1
@SpringBootTest
2
@ActiveProfiles("test")
3
@AutoConfigureMockMvc
4
class MyliquibasePlanetApplicationTests {
5
 
6
   @Autowired
7
   private MockMvc mockMvc;
8
 
9
   @Test
10
   void contextLoads() {
11
   }
12
 
13
   @Test
14
   public void getAllEmployees() throws Exception {
15
      this.mockMvc.perform(get("/getAllEmployees"))
16
                  .andDo(print())
17
                  .andExpect(status().isOk())
18
                  .andExpect(content().string("[{\"id\":1,\"firstName\":\"Foo\",\"lastName\":\"Bar\",\"country\":\"Sweden\"}]"));
19
   }
20
 
21
}


Run the test:

Shell
 




xxxxxxxxxx
1


 
1
$ mvn test -Dspring-boot.run.profiles=test


Obviously this fails because we do not have a running database:

Shell
 




xxxxxxxxxx
1


 
1
2020-04-04 13:54:28.652 ERROR 6609 --- [ main] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Exception during pool initialization.
2
org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
3
...
4
Caused by: java.net.ConnectException: Connection refused (Connection refused)
5
...


The solution for this problem is using Testcontainers.

3. Use Testcontainers

We need a PostgreSQL database in order to run the integration test we wrote. We can do so by using the Spring Boot Testcontainers. In order to use these, we need to insert the spring-cloud-starter, embedded-postgresql and the junit-jupiter testcontainers dependencies to our pom.

XML
 




xxxxxxxxxx
1
18


 
1
<dependency>
2
    <groupId>org.testcontainers</groupId>
3
    <artifactId>junit-jupiter</artifactId>
4
    <version>1.13.0</version>
5
    <scope>test</scope>
6
</dependency>
7
<dependency>
8
    <groupId>org.springframework.cloud</groupId>
9
    <artifactId>spring-cloud-starter</artifactId>
10
    <version>2.2.2.RELEASE</version>
11
    <scope>test</scope>
12
</dependency>
13
<dependency>
14
    <groupId>com.playtika.testcontainers</groupId>
15
    <artifactId>embedded-postgresql</artifactId>
16
    <version>1.43</version>
17
    <scope>test</scope>
18
</dependency>


We add a file test/resources/bootstrap-test.properties where we enable the embedded PostgreSQL database and where we define the Docker image to be used and the database access credentials.

Properties files
 




xxxxxxxxxx
1


 
1
embedded.postgresql.enabled=true
2
embedded.postgresql.dockerImage=postgres:latest
3
embedded.postgresql.user=postgres
4
embedded.postgresql.password=root


We also move the application-test.properties we created in our previous post to the test/resources directory. We change the datasource properties in order to use the properties as we configured in the bootstrap-test.properties file:

Properties files
 




xxxxxxxxxx
1


 
1
spring.datasource.url=jdbc:postgresql://${embedded.postgresql.host}:${embedded.postgresql.port}/postgres
2
spring.datasource.username=${embedded.postgresql.user}}
3
spring.datasource.password=${embedded.postgresql.password}
4
 
5
spring.liquibase.change-log=classpath:/db/changelog/db.changelog-master.xml
6
spring.liquibase.contexts=test


Last thing to do is to add the Testcontainer to our integration test. Beware that the configuration for using Testcontainers which is being used, is only available from Spring Boot 2.2.6, see the corresponding blog.

We add the @Testcontainers annotation, we create a PostgreSQL instance annotated with @Container and we add the PostgreSQL properties annotated with the @DynamicPropertyResource. The latter will allow the PostgreSQL related beans to communicate with the PostgreSQL instance running in the Testcontainers-managed Docker container.

Java
 




xxxxxxxxxx
1
30


1
@SpringBootTest
2
@ActiveProfiles("test")
3
@AutoConfigureMockMvc
4
@Testcontainers
5
class MyliquibasePlanetApplicationTests {
6
 
7
   @Autowired
8
   private MockMvc mockMvc;
9
 
10
   @Container
11
   static PostgreSQLContainer<?> postgreSQL = new PostgreSQLContainer<>();
12
 
13
   @DynamicPropertySource
14
   static void postgreSQLProperties(DynamicPropertyRegistry registry) {
15
      registry.add("spring.datasource.url", postgreSQL::getJdbcUrl);
16
      registry.add("spring.datasource.username", postgreSQL::getUsername);
17
      registry.add("spring.datasource.password", postgreSQL::getPassword);
18
   }
19
 
20
   @Test
21
   void contextLoads() {
22
   }
23
 
24
   @Test
25
   public void getAllEmployees() throws Exception {
26
      this.mockMvc.perform(get("/getAllEmployees")).andDo(print()).andExpect(status().isOk())
27
            .andExpect(content().string("[{\"id\":1,\"firstName\":\"Foo\",\"lastName\":\"Bar\",\"country\":\"Sweden\"}]"));
28
   }
29
 
30
}


Run the test again:

Shell
 




xxxxxxxxxx
1


 
1
$ mvn test -Dspring-boot.run.profiles=test


Our integration test now succeeds successfully.

4. Create addEmployee Integration Test

In order to complete the integration test, we also add an integration test for the addEmployee REST interface. We want to validate whether the employee is really added to the database. We therefore extend the EmployeeDAO with a getEmployee method:

Java
 




xxxxxxxxxx
1


 
1
public Employee getEmployee(final String firstName, final String lastName, final String country) {
2
    return jdbcTemplate.queryForObject("SELECT * FROM EMPLOYEE WHERE FIRST_NAME = ? AND LAST_NAME = ? AND COUNTRY = ?",
3
            new EmployeeRowMapper(), firstName, lastName, country);
4
}


The addEmployee integration test is the following:

Java
 




xxxxxxxxxx
1
27


 
1
@Autowired
2
private JdbcTemplate jdbcTemplate;
3
 
4
@Autowired
5
private EmployeeDao employeeDao;
6
 
7
...
8
 
9
@Test
10
@Transactional
11
public void addEmployee() throws Exception {
12
   int rowsBefore = JdbcTestUtils.countRowsInTable(jdbcTemplate, "Employee");
13
 
14
   this.mockMvc.perform(post("/addEmployee")
15
             .param("firstName", "John")
16
             .param("lastName", "Doe")
17
             .param("country", "Belgium"))
18
             .andDo(print())
19
             .andExpect(status().isOk())
20
             .andExpect((content().string("Saved Employee")));
21
 
22
   int rowsAfter = JdbcTestUtils.countRowsInTable(jdbcTemplate, "Employee");
23
 
24
   Employee result = employeeDao.getEmployee("John", "Doe", "Belgium");
25
   Assert.notNull(result, "No result available");
26
   Assert.isTrue(rowsBefore + 1 == rowsAfter, "Employee is not added");
27
}


We inject the employeeDAO because we want to verify whether the employee is added to the database in Line 24. The test is annotated with @Transactional, this will ensure that the database changes during the test are rollbacked after the test. If we do not add this annotation, the getAllEmployees integration test would fail when it is executed after the addEmployee test (because of an extra record in the database). We use JdbcTestUtils and the injected jdbcTemplate to verify the number of rows before and after the REST call.

5. Conclusion

We have been using Testcontainers in order to execute some integration tests. Using Testcontainers is fairly easy and it gives us the opportunity to create integration tests without the need of pre-installed components. We just add a Testcontainer which is started at the beginning of the integration test and use the component from within the running integration tests.

 

 

 

 

Top