dogmadogmassage.com

YugabyteDB Integration Testing with Spring Boot and Testcontainers

Written on

Chapter 1: Introduction to YugabyteDB and Spring Boot

In this guide, we will illustrate how to set up a straightforward integration testing environment for YugabyteDB using Spring Boot and Testcontainers. Testcontainers is an innovative tool that simplifies the process of creating Docker images specifically for testing, with a focus on its use for testing interactions with the Yugabyte database.

What is YugabyteDB?

According to its official site, YugabyteDB is a highly scalable distributed SQL database known for its fault tolerance and data durability. It allows for deployments across various data centers and cloud environments, ensuring optimal performance and availability.

What is Spring Boot?

As described on its website, Spring Boot simplifies the creation of standalone, production-ready Spring-based applications that can be executed with minimal configuration.

What is Docker?

Docker is an open platform designed for developing, shipping, and running applications. It allows developers to decouple their applications from the underlying infrastructure, facilitating quicker software delivery.

What is Testcontainers?

Testcontainers is an open-source framework that provides disposable, lightweight instances of databases, message brokers, web browsers, or any service that can run in a Docker container.

Before We Begin

To follow along, ensure you have the following installed:

  • Docker or an alternative like Rancher or Podman.
  • Git, which is essential for quickly setting up and running the demonstration.

How It All Started

To initiate the project, we utilized Spring Boot via start.spring.io and incorporated Maven dependencies including Lombok, Testcontainers, and the PostgreSQL Driver.

Getting the Code

The source code is accessible on GitHub. You can clone it using the following command:

Code Overview

The DBConnectionProvider Class

The DBConnectionProvider.java class is responsible for managing database connections and implements the DbConnection interface:

public class DBConnectionProvider implements DBConnection {

private final String url;

private final String username;

private final String password;

public DBConnectionProvider(String url, String username, String password) {

this.url = url;

this.username = username;

this.password = password;

}

@Override

public Connection getConnection() {

try {

return DriverManager.getConnection(url, username, password);

} catch (Exception e) {

throw new RuntimeException(e);

}

}

}

The CustomerService Class

The Customer.java class defines a Customer object, while CustomerService.java manages customer-related operations. The CustomerService constructor takes an instance of DbConnection, which is assigned to a private variable:

public CustomerService(DBConnection dbConnection) {

this.dbConnection = dbConnection;

}

The methods getCustomer() and createCustomer() utilize the Connection object to select and insert data into the Customer table, respectively.

The Tests

The CustomerServiceTest class contains three tests. Here, we use several annotations:

@SpringBootTest

@Testcontainers

@TestMethodOrder(MethodOrderer.MethodName.class)

class CustomerServiceTest {

The @SpringBootTest annotation enables Spring Boot's testing support, while @Testcontainers integrates Testcontainers for managing Docker containers during tests. The @TestMethodOrder(MethodOrderer.MethodName.class) annotation ensures that tests run in alphabetical order based on their method names.

We also initialize some variables:

static YugabyteDBYSQLContainer yugabyteDBYSQLContainer = new YugabyteDBYSQLContainer("yugabytedb/yugabyte:latest")

.waitingFor(Wait.defaultWaitStrategy());

This establishes a static variable representing a YugabyteDBYSQLContainer instance from Testcontainers.

Running the Tests

To build the project without executing tests, run the following command in the project directory:

mvn clean spring-boot:run -DskipTests

The anticipated output will be:

[INFO] ------------------------------------------------------------------------

[INFO] BUILD SUCCESS

[INFO] ------------------------------------------------------------------------

[INFO] Total time: 4.265 s

[INFO] Finished at: 2024-03-23T14:35:00Z

[INFO] ------------------------------------------------------------------------

Now, let's run just the tests:

mvn test -Dtest="CustomerServiceTest"

Expected output:

[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 16.86 s -- in com.example.yugabytedbtestcontainersspringboot.CustomerServiceTest

[INFO]

[INFO] Results:

[INFO]

[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0

[INFO] ------------------------------------------------------------------------

[INFO] BUILD SUCCESS

[INFO] ------------------------------------------------------------------------

[INFO] Total time: 18.925 s

[INFO] Finished at: 2024-03-23T14:36:14Z

[INFO] ------------------------------------------------------------------------

Observing the Logs

Monitor the logs carefully to follow the process, including compatibility checks for the Docker version and the container's readiness:

14:36:00.027 [main] INFO org.testcontainers.utility.RyukResourceReaper -- Ryuk started - will monitor and terminate Testcontainers containers on JVM exit

...

Running the Tests with Docker

To simultaneously build and run the tests, execute:

mvn clean package

Summary

In this guide, we explored how to implement YugabyteDB integration testing utilizing Spring Boot and Testcontainers. By leveraging Testcontainers, developers can seamlessly set up Docker images tailored for testing. The successful completion of tests provides developers with confidence in using Spring Boot and Testcontainers for efficient and reliable YugabyteDB integration testing.

Stay tuned for more experiments!

Additional Readings

References:

Thanks for reading! 👏 Please clap for the story (50 claps) to help spread the article 🌐 Share it on social media ➕ More stories about Programming, Career, AI, and more. 🔔 Follow me: Medium | LinkedIn | Twitter ✉️ Subscribe to the newsletter.

Chapter 2: Video Demonstrations

This video titled "Spring Boot Testcontainers - Integration Testing made easy!" provides a practical overview of using Testcontainers for integration testing with Spring Boot.

The second video, "Spring Boot Testing part 2: Integration Testing with Testcontainers," delves deeper into effective testing strategies with Spring Boot and Testcontainers.

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Understanding Communication Styles That Can Ruin a Marriage

Explore communication styles that can threaten the stability of a marriage and learn how to foster healthier conversations.

Embracing Change: Nurturing Growth Beyond Medium

Discover the lessons learned during a writing hiatus and the journey of self-discovery that followed.

2024 Could Be the Toughest Year for Earth Due to Solar Storms

2024 may challenge Earth with intense solar activity, risking technology and networks.

Essential Qualities for Meaningful Relationships Explored

Discover the key attributes that build strong friendships and romantic partnerships, enhancing emotional connections and personal growth.

Unlocking the Power of Natural Luck Through Self-Alignment

Discover how to activate natural luck through alignment and acceptance of love in your life, leading to transformative experiences.

Strategic Insights for Investors in 2022: Key Themes Unveiled

Discover the essential strategies for navigating the challenges of 2022, focusing on local dynamics, technology, and human behavior.

E-commerce Trends and Financial Market Insights for 2022

An overview of e-commerce trends and financial market statistics for 2022, along with insights into consumer behavior and investment strategies.

Essential GitHub Repositories Every Developer Should Explore

Discover ten incredible GitHub repositories that can enhance your skills and knowledge in web development and programming.