How to use Testcontainers with spring 5 and Junit Jupiter 5

Mohammed Hewedy
2 min readJul 10, 2019

--

Photo by Anisur Rahman on Unsplash

I’ve learned the hard way that using an Integration test database different than the Production database is a not so good experience.

Hence I decided to use the same database in my next project.

So I am trying to use PostgreSQL database in Integration tests, and I am trying to use it via Testcontainers.

It is a typical spring boot project (2.2.0) which comes by default with JUnit Jupiter 5.

Let's start with the pom.xml

<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<version>1.11.4</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<version>1.11.4</version>
<scope>test</scope>
</dependency>

And I’ve created a static reference to my container:

import org.testcontainers.containers.PostgreSQLContainer as LibPostgreSQLContainer

val sharedPostgreSQLContainer = PostgreSQLContainer()

class PostgreSQLContainer :
LibPostgreSQLContainer<PostgreSQLContainer>("postgres:11.4-alpine") {

override fun start() {
super.start()
System.setProperty("spring.datasource.url", sharedPostgreSQLContainer.jdbcUrl)
System.setProperty("spring.datasource.username", sharedPostgreSQLContainer.username)
System.setProperty("spring.datasource.password", sharedPostgreSQLContainer.password)
}
}

And in Spring Test I am referring to this shared instance:

@SpringBootTest
@Testcontainers
class ApplicationTests {

companion object {
@Container
val postgreSQLContainer = sharedPostgreSQLContainer
}

@Test
fun contextLoads() {
}

}

That’s all folks.

References:

--

--

Mohammed Hewedy
Mohammed Hewedy

Responses (1)