DEV Community

Roger Viñas Alcon for Adevinta Spain

Posted on • Updated on

Testing a dockerized Spring Boot Application

In this sample we will create a 🍀 Spring Boot Application with a simple /hello endpoint and then distribute it as a 🐳 Docker image

And of course we want to ensure the Docker image works, so we will test it using Testcontainers 🤩


Spoiler alert! 👇

GitHub logo rogervinas / spring-boot-docker

🐳 Spring Boot with Docker

Ready? Let's go!

1) We start at Spring Initialzr and create an empty Spring Boot project with Webflux and Kotlin

2) Then we add this simple test

@SpringBootTest(webEnvironment = RANDOM_PORT)
class ApplicationTests {

  private var port: Int = 0

  fun `should say hello`() {
    val responseBody = WebClient.builder()
      .exchangeToMono { response ->
Enter fullscreen mode Exit fullscreen mode

3) And we add this simple implementation ...

class HelloController {

    fun hello() = "hello!"
Enter fullscreen mode Exit fullscreen mode

... and now our test is 🟩👏

4) Next we need to generate a docker image ... 🤔

Some alternatives are documented in Spring Boot with Docker and Topical Guide on Docker

And luckily for us, it is as easy as use the task bootBuildImage of the Spring Boot's Gradle plugin:

./gradlew bootBuildImage
Enter fullscreen mode Exit fullscreen mode

So far so good! 😁

Now we have to test the generated docker image ...

5) First we use org.unbroken-dome.test-sets to create a new test source root named container-test:

plugins {
  id("org.unbroken-dome.test-sets") version "4.0.0"

testSets {


Enter fullscreen mode Exit fullscreen mode

Note that bootBuildImage task is executed before container-test task, so we ensure we are always testing the docker image we've just built from the current source code

6) Then we create test using Testcontainers and JUnit5

class ApplicationContainerTests {

  companion object {

    private const val appPort = 8080

    private val app = KGenericContainer(System.getProperty("docker.image"))

  fun `should say hello`() {
    // ...
Enter fullscreen mode Exit fullscreen mode

7) Last thing we need to do is set the value of the system property docker.image before running any test:

tasks.withType<Test> {
    systemProperty("docker.image", "${}:${project.version}")
Enter fullscreen mode Exit fullscreen mode

As ${}:${project.version} is the default value used by bootBuildImage task

And that is all! Happy coding! 💙

Ofertas Backend

Discussion (0)