Testcontainers is an open-source Java library that supports automated integration testing using Docker containers. This topic describes how to connect to and use OceanBase Cloud with Testcontainers.
Prerequisites
- You have downloaded, installed, and started Docker.
- You have downloaded and installed IntelliJ IDEA.
- You have downloaded JDK 1.8.0.
- (Optional) You have downloaded Maven and configured it in IntelliJ IDEA.
Post-installation check
Check whether Docker is installed successfully:
docker -vYou do not need to manually start Docker. It will be automatically started and stopped when you run the sample program in the following steps.
Check whether JDK is installed successfully:
java -versionCheck whether Maven is installed successfully:
mvn -version(Optional) Check whether Maven is correctly configured in IntelliJ IDEA:
This topic provides only a simple sample project for your reference. If you want to develop a more complex example, you can download Maven of a version suitable for your development environment and configure it in IntelliJ IDEA by following these steps.
Check whether Maven is installed successfully:
mvn -versionOpen IntelliJ IDEA, click IntelliJ IDEA > Settings > Build,Execution,Development > Build Tools > Maven, and configure the Maven home path to the installation directory of Maven.
Procedure
Extract the downloaded sample project code and open it using IntelliJ IDEA.
Run the sample project ExampleTest located in src > test > java.
If the following result is returned, the database connection is successful and the sample project is executed correctly.
... 53575 [main] INFO com.oceanbase.example.ExampleTest - Connect to OceanBase docker container successfully. 53577 [main] INFO com.oceanbase.example.ExampleTest - Prepare database and table. 53892 [main] INFO com.oceanbase.example.ExampleTest - Insert data to table `testcontainers`.`person`. 53928 [main] INFO com.oceanbase.example.ExampleTest - Query rows from `testcontainers`.`person`. 53932 [main] INFO com.oceanbase.example.ExampleTest - Row 0: name Adam, age 28. 53932 [main] INFO com.oceanbase.example.ExampleTest - Row 1: name Eve, age 26.
Sample project overview
Click Testcontainers to download the project code, which is a compressed file named TestcontainersDemo.zip.
After extracting it, you will get a folder named TestcontainersDemo. The directory structure is as follows:
JDBCDemo
├── src
│ └── test
│ └── java
│ └── ExampleTest.java
└── pom.xml
File description:
src: The root directory for source code.test: The main code directory, containing the application's primary logic.java: The Java source code directory.ExampleTest.java: The main class, containing logic such as creating tables and inserting data.pom.xml: The configuration file for the Maven project, used to manage project dependencies and build settings.
Introduction to pom.xml code
The pom.xml file is the configuration file for the Maven project, defining information such as the project's dependencies, plugins, and build rules. Maven is a Java project management tool that can automatically download dependencies, compile, and package projects.
The code in this pom.xml file mainly includes the following parts:
File declaration statement.
Declares that this file is an XML file, using XML version
1.0and character encodingUTF-8.Code:
<?xml version="1.0" encoding="UTF-8"?>Configure the POM namespace and POM model version.
- Use
xmlnsto specify the POM namespace ashttp://maven.apache.org/POM/4.0.0. - Use
xmlns:xsito specify the XML namespace ashttp://www.w3.org/2001/XMLSchema-instance. - Use
xsi:schemaLocationto specify the POM namespace,http://maven.apache.org/POM/4.0.0, and the location of its XSD file,http://maven.apache.org/xsd/maven-4.0.0.xsd. - Use the
<modelVersion>element to specify the POM model version used by this POM file as4.0.0.
Code:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <!-- Other configurations --> </project>- Use
Configure the basic information.
- Use
<groupId>to specify the project's organization ascom.example. - Use
<artifactId>to specify the project name asJDBCDemo. - Use
<version>to specify the project version as1.0-SNAPSHOT.
Sample code:
<groupId>org.example</groupId> <artifactId>JDBCDemo</artifactId> <version>1.0-SNAPSHOT</version>- Use
Configure the external packages that the project depends on. Each dependency is defined with a groupId, artifactId, and version.
- Use
<groupId>to specify the organization to which the dependency belongs. - Use
<artifactId>to specify the name of the dependency. - Use
<version>to specify the version of the dependency. - Use
<scope>to specify the scope of the dependency, indicating that it is used only during testing.
Sample code:
<dependencies> <dependency> //If you are using MySQL JDBC, you need to replace the groupId, artifactId, and version information here. <groupId>com.oceanbase</groupId> <artifactId>oceanbase-client</artifactId> <version>2.4.9</version> </dependency> <dependency> <groupId>org.testcontainers</groupId> <artifactId>oceanbase</artifactId> <version>1.19.7</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> <version>2.17.1</version> <scope>test</scope> </dependency> </dependencies>- Use
Introduction to ExampleTest.java
The ExampleTest.java file is part of the sample application. It uses the Testcontainers framework and JUnit to create a testable Java class.
It sets up a test environment that runs an OceanBase Cloud database container using Testcontainers and defines some basic settings for the test class.
Sample code:
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; // Test class definition begins public class ExampleTest { // Create an SLF4J Logger instance to log messages for the ExampleTest class. private static final Logger LOG = LoggerFactory.getLogger(ExampleTest.class); // Create an OceanBase container instance, use the specified Docker image, and configure environment variables. public static final OceanBaseCEContainer CONTAINER = new OceanBaseCEContainer("oceanbase/oceanbase-ce:4.2.2") .withEnv("MODE", "slim") // Set the environment variable MODE to slim. .withEnv("FASTBOOT", "true") // Set the environment variable FASTBOOT to true. .withLogConsumer(new Slf4jLogConsumer(LOG)); // Add a log consumer to record container logs using SLF4J. // Call this method before all tests to prepare the environment. @BeforeClass public static void startContainers() { // Start the CONTAINER asynchronously and wait for it to complete. Startables.deepStart(Stream.of(CONTAINER)).join(); // Output information related to the container startup, including the Docker image name, container host address, and mapped ports. LOG.info( "OceanBase docker container started, image: {}, host: {}, sql port: {}, rpc port:{}.", CONTAINER.getDockerImageName(), CONTAINER.getHost(), CONTAINER.getMappedPort(2881), CONTAINER.getMappedPort(2882)); } // Call this method after all tests are completed to clean up resources. @AfterClass public static void closeContainers() { // Close the container. CONTAINER.close(); // Record container stop logs LOG.info("OceanBase docker container stopped."); } ```It writes the test logic.
Sample code:
// Test database insertion and query operations @Test public void test() { // Database and Table Names String database = "testcontainers"; String table = "person"; // The fully qualified names of databases and tables, which must be escaped with backticks to avoid conflicts with SQL keywords. String tableName = String.format("`%s`.`%s`", database, table); // Output Log for Attempting to Connect to OceanBase Container LOG.info( "Try to connect to OceanBase docker container with url: {}.", CONTAINER.getJdbcUrl()); // Create a database connection to the OceanBase container try (Connection connection = CONTAINER.createConnection("?useSSL=false")) { LOG.info("Connect to OceanBase docker container successfully."); LOG.info("Prepare database and table.");It creates a table.
Sample code:
// Create a database and table try (Statement statement = connection.createStatement()) { statement.execute("CREATE DATABASE IF NOT EXISTS " + database); statement.execute("USE " + database); statement.execute( "CREATE TABLE IF NOT EXISTS " + table + " (name VARCHAR(50), age INT)"); } catch (SQLException e) { throw new RuntimeException(e); }It inserts data.
Code:
LOG.info("Insert data to table {}.", tableName); try (PreparedStatement ps = connection.prepareStatement("INSERT INTO " + tableName + " values(?, ?)")) { ps.setString(1, "Adam"); ps.setInt(2, 28); ps.executeUpdate(); ps.setString(1, "Eve"); ps.setInt(2, 26); ps.executeUpdate(); }Query data.
Code:
LOG.info("Query rows from {}.", tableName); try (PreparedStatement ps = connection.prepareStatement( "SELECT * from " + tableName, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) { ResultSet rs = ps.executeQuery(); int count = 0; while (rs.next()) { LOG.info("Row {}: name {}, age {}.", count++, rs.getString(1), rs.getInt(2)); }Exception handling.
Any exception that occurs during the execution of the above database operations will be caught, and error information along with stack trace details will be printed.
Code:
} catch (SQLException e) { // If an exception occurs, a runtime exception is thrown. throw new RuntimeException(e); }
Complete sample code
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.oceanbase.example</groupId>
<artifactId>testcontainers-java</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.oceanbase</groupId>
<artifactId>oceanbase-client</artifactId>
<version>2.4.9</version>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>oceanbase</artifactId>
<version>1.19.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.17.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
package com.oceanbase.example;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testcontainers.containers.output.Slf4jLogConsumer;
import org.testcontainers.lifecycle.Startables;
import org.testcontainers.oceanbase.OceanBaseCEContainer;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.stream.Stream;
public class ExampleTest {
private static final Logger LOG = LoggerFactory.getLogger(ExampleTest.class);
public static final OceanBaseCEContainer CONTAINER =
new OceanBaseCEContainer("oceanbase/oceanbase-ce:4.2.2")
.withEnv("MODE", "slim")
.withEnv("FASTBOOT", "true")
.withLogConsumer(new Slf4jLogConsumer(LOG));
@BeforeClass
public static void startContainers() {
Startables.deepStart(Stream.of(CONTAINER)).join();
LOG.info(
"OceanBase docker container started, image: {}, host: {}, sql port: {}, rpc port:{}.",
CONTAINER.getDockerImageName(),
CONTAINER.getHost(),
CONTAINER.getMappedPort(2881),
CONTAINER.getMappedPort(2882));
}
@AfterClass
public static void closeContainers() {
CONTAINER.close();
LOG.info("OceanBase docker container stopped.");
}
@Test
public void test() {
String database = "testcontainers";
String table = "person";
String tableName = String.format("`%s`.`%s`", database, table);
LOG.info(
"Try to connect to OceanBase docker container with url: {}.",
CONTAINER.getJdbcUrl());
try (Connection connection = CONTAINER.createConnection("?useSSL=false")) {
LOG.info("Connect to OceanBase docker container successfully.");
LOG.info("Prepare database and table.");
try (Statement statement = connection.createStatement()) {
statement.execute("CREATE DATABASE IF NOT EXISTS " + database);
statement.execute("USE " + database);
statement.execute(
"CREATE TABLE IF NOT EXISTS " + table + " (name VARCHAR(50), age INT)");
} catch (SQLException e) {
throw new RuntimeException(e);
}
LOG.info("Insert data to table {}.", tableName);
try (PreparedStatement ps =
connection.prepareStatement("INSERT INTO " + tableName + " values(?, ?)")) {
ps.setString(1, "Adam");
ps.setInt(2, 28);
ps.executeUpdate();
ps.setString(1, "Eve");
ps.setInt(2, 26);
ps.executeUpdate();
}
LOG.info("Query rows from {}.", tableName);
try (PreparedStatement ps =
connection.prepareStatement(
"SELECT * from " + tableName,
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY)) {
ResultSet rs = ps.executeQuery();
int count = 0;
while (rs.next()) {
LOG.info("Row {}: name {}, age {}.", count++, rs.getString(1), rs.getInt(2));
}
assert count == 2;
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
References
- Testcontainers for Java official documentation
- To use the OceanBase Docker image, you need to use a GenericContainer. You can refer to the OceanBase Module documentation.