Home » Enterprise Java » spring » Boot » DB Integration Tests with Spring Boot and Testcontainers

About Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).

DB Integration Tests with Spring Boot and Testcontainers

Hello. In this tutorial, we will explore the Testcontainers to perform integration tests for the jpa repositories in a Spring Boot app.

1. Introduction

Testcontainers is a library that provides a clean way for writing the integration and end-to-end tests for the jpa repositories. In this example, we will create a simple rest api application to persist the data in the database and make use of the Postgres test container to have the jpa testing. For test containers to work ensure to have the Docker up and running on your machine. If someone needs to go through the Docker installation, please watch this video.

2. DB Integration Tests with Spring Boot and Testcontainers

Let us dive into some practice stuff and I am hoping that you are aware of the spring boot basics.

2.1 Tools Used for Spring boot application and Project Structure

We are using Eclipse Kepler SR2, JDK 8, and Maven. In case you’re confused about where you should create the corresponding files or folder, let us review the project structure of the spring boot application.

Spring Boot Testcontainers - project structure
Fig. 1: Project structure

Let us start building the application!

3. Creating a Spring Boot application

Below are the steps involved in developing the application.

3.1 Maven Dependency

In the pom.xml file we will define the required dependencies.


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">






  <description>Demo project for Spring Boot and Testcontainers</description>



    <version>2.5.6</version> <!-- lookup parent from repository -->




3.2 Application properties file

Create a properties file in the resources folder and add the following content to it. The file will contain information about the database connectivity and spring jpa. For this tutorial, we will use the Postgresql database. I already have the container up and running on the localhost:5433.


#database settings
##sample url - jdbc:postgresql://hostname:port/your_db_name
#jpa settings

3.3 Java Classes

Let us write the important java class(es) involved in this tutorial. The other non-important classes for this tutorial like the main, controller, service, exceptions, and bootstrap can be downloaded from the Downloads section.

3.3.1 Model class

Create a model class that will be responsible for schema and data in the sql table.


package com.springboot.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;

// entity table.

@Table(name = "book")
public class Book {

  @GeneratedValue(strategy = GenerationType.AUTO)
  int id;
  String author;
  String title;
  String genre;
  String publisher;
  int quantity;

3.3.2 Repository interface

Add the following code to the repository interface that extends the JpaRepository. The interface consists of custom methods to clearly understand the jpa and test container implementation.


package com.springboot.repository;

import com.springboot.model.Book;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

public interface BookRepository extends JpaRepository<Book, Integer> {

	// custom jpa method to find books by genre.
	List<Book> findBooksByGenre(String genre);

	// custom jpa method to find books by quantity.
	List<Book> findBooksByQuantityGreaterThanEqual(int quantity);

	// custom jpa method to find a book by name.
	Book findFirstByTitle(String title);

3.4 Test cases implementation

To set up the test container in this tutorial we will need Docker (for pulling the image used by the test container) and the required testcontainer library. The dependency is already added to the pom.xml file.

3.4.1 Starting and stopping the container

Spring boot provides a feature called the slice test which is a neat way to test the horizontal slices of the application. To test the jpa we will make use of the Book repository interface created above. Now to configure a database that is exclusively available for our tests we will create a BaseIT class in the test folder.


package com.springboot.repository;

import org.testcontainers.containers.PostgreSQLContainer;

// using the singleton container approach to improve the performance of our tests.
public abstract class BaseIT {

  static PostgreSQLContainer<?> container;

  static {
    container = new PostgreSQLContainer<>("postgres:alpine")


3.4.2 Running the tests

With this done we can write our tests. We now will create a class named BookRepositoryTest.java that will extend the BaseIT class. The class will consist of the test cases which we can run as Junit tests.


package com.springboot.repository;

import static org.assertj.core.api.Assertions.assertThat;
import static org.testcontainers.shaded.org.apache.commons.lang.RandomStringUtils.randomAlphabetic;

import com.github.javafaker.Faker;
import com.springboot.model.Book;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;

// annotation is used to test the jpa repositories
// by default uses the embedded in-memory database for testing
// annotation used to configure a test database instead of application
// defined or auto-configured datasource
@AutoConfigureTestDatabase(replace = Replace.NONE)
class BookRepositoryTest extends BaseIT {

  private static final Faker FAKER = new Faker(Locale.ENGLISH);

  BookRepository objUnderTest;

  void shouldFindBookById() {
    Book actual = create(randomAlphabetic(5), randomAlphabetic(5), 1);

    Book expected = objUnderTest.findById(actual.getId()).get();

  void shouldFindBooksByGenre() {
    String genre = "Fable";
    List<Book> actual = prepare(2, randomAlphabetic(5), genre, 10);

    List<Book> expected = objUnderTest.findBooksByGenre(genre);

  void shouldFindBooksByGenre_ReturnAnEmptyList() {
    List<Book> actual = prepare(2, randomAlphabetic(2), "Fiction", 1);


  void shouldFindBooksByQuantity() {
    int quantity = 60;
    List<Book> actual = prepare(5, randomAlphabetic(5), randomAlphabetic(5), quantity);

    List<Book> expected = objUnderTest.findBooksByQuantityGreaterThanEqual(quantity);

  void shouldFindBooksByQuantity_ReturnAnEmptyList() {
    List<Book> actual = prepare(2, randomAlphabetic(2), randomAlphabetic(5), 3);


  void shouldFindFirstBookByTitle() {
    Book book1 = create("Harry Potter", "Fantasy Fiction", 5);
    Book book2 = create("Harry Potter", "Fantasy Fiction", 10);
    List<Book> actual = Arrays.asList(book1, book2);


    Book expected = objUnderTest.findFirstByTitle("Harry Potter");

  //helper methods.

  private List<Book> prepare(int iterations, String title, String genre, int quantity) {
    List<Book> books = new ArrayList<>();
    for (int i = 0; i < iterations; i++) {
      books.add(create(title, genre, quantity));
    return books;

  private Book create(String title, String genre, int quantity) {
    return Book.builder()

4. Run the Testcases

To execute the repository test cases, right-click on the BookRepositoryTest.java class, Run As -> Junit Tests. If everything goes well the test cases will be passed successfully as shown in Fig. 2. The test container will download the given docker image to run the repository test cases.

Spring Boot Testcontainers - running the test cases
Fig. 2: Running the test cases

5. Project Demo

Run the implementation file (i.e. TestContainersApp.java). To test the application endpoints we will use the postman tool. However, you’re free to use any tool of your choice for interacting with the application endpoints.

Application endpoints

-- get a book by id -- 

-- get books --

-- get books by genre --

-- get books by quantity --

That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!

6. Summary

In this tutorial, we learned the implementation of test containers to test the repository self or custom methods. You can download the sample application as an Eclipse project in the Downloads section.

7. Download the Project

This was an example of test containers implementation in a sping application to test the repository methods.

You can download the full source code of this example here: DB Integration Tests with Spring Boot and Testcontainers

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area


Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments