### Start Default Qdrant Container Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/qdrant.md Instantiates and starts a default Qdrant container. This is a basic example for getting started. ```java try (QdrantContainer qdrant = new QdrantContainer()) { qdrant.start(); // Use the container } ``` -------------------------------- ### Start Default ChromaDB Container Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/chromadb.md Instantiate a default ChromaDB container. This example shows the basic setup for running a ChromaDB instance with Testcontainers. ```java private static ChromaDBContainer chromaDBContainer; @BeforeAll static void setUp() { chromaDBContainer = new ChromaDBContainer(DockerImageName.parse("chromadb/chroma:latest")); chromaDBContainer.start(); } @AfterAll static void tearDown() { chromaDBContainer.stop(); } ``` -------------------------------- ### Start Datastore Emulator Container Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/gcloud.md Starts a Datastore emulator container for testing. This setup is essential for running tests that interact with Datastore locally. ```java DatastoreEmulatorContainer datastore = new DatastoreEmulatorContainer(GoogleCloudImage.of("gcr.io/google.com/cloudsdktool/google-cloud-cli:emulators")); datastore.start(); ``` -------------------------------- ### Java Init Function Example Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/jdbc.md Example of a public static Java method that can be used as an init function for database setup via JDBC URL. It accepts a `java.sql.Connection`. ```java public class JDBCDriverTest { public static void sampleInitFunction(Connection connection) throws SQLException { // e.g. run schema setup or Flyway/liquibase/etc DB migrations here... } ... ``` -------------------------------- ### Setup k6 Container Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/k6.md Starts a K6 container instance with a specified script and command-line options. Ensure the script file exists in the specified path. ```java K6Container k6Container = new K6Container(DockerImageName.parse("grafana/k6:latest")) .withScript("scripts/test.js") .withCommand("--vus=10", "--duration=1m", "--summary-trend-stats=all", "--log-output=system") .withEnv("K6_SCRIPT_VAR", "my-script-variable"); k6Container.start(); ``` -------------------------------- ### MySQL Container Definition Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/mysql.md Example of how to start a MySQL container instance in a Java application. ```java import org.junit.jupiter.api.Test; import org.testcontainers.containers.MySQLContainer; public class MySQLContainerTest { @Test public void container() { try (MySQLContainer mysql = new MySQLContainer<>("mysql:8.0")) { mysql.start(); // use the container } } } ``` -------------------------------- ### Start Pinecone Local Container Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/pinecone.md Instantiate and start a Pinecone Local container. This is the primary way to get a Pinecone instance running for your tests. ```java PineconeLocalContainer pinecone = new PineconeLocalContainer(); pinecone.start(); ``` -------------------------------- ### Start a K3s Server Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/k3s.md Use this snippet to start a K3s server instance within a Testcontainers environment. This is the basic setup for interacting with K3s. ```java try (var k3s = new K3sContainer(K3sContainer.K3sImage.ofPlatform("linux/amd64"))) { k3s.start(); // Use k3s container } ``` -------------------------------- ### Start a MinIO Container Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/minio.md Instantiate and start a MinIO container for use in tests. This is the basic setup for using MinIO with Testcontainers. ```java MinIOContainer minioContainer = new MinIOContainer(); minioContainer.start(); ``` -------------------------------- ### MS SQL Server Container Definition Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/mssqlserver.md Example of how to define and start an MS SQL Server container instance in Java. Requires accepting the EULA. ```java try (MSSQLServerContainer mssqlserver = new MSSQLServerContainer<>("mcr.microsoft.com/mssql/server:2017-CU12")) { mssqlserver.acceptLicense(); mssqlserver.start(); // Use the container, e.g. get JDBC URL String jdbcUrl = mssqlserver.getJdbcUrl(); System.out.println(jdbcUrl); } ``` -------------------------------- ### LLdapContainer Usage Example Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/ldap.md Start a LLDAP container instance from a Java application. ```java LLdapContainer lldapContainer = new LLdapContainer(); ll dapContainer.start(); ``` -------------------------------- ### Start Milvus Container with Default Config Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/milvus.md Demonstrates how to start a Milvus container with its default configuration. This is useful for basic testing scenarios. ```java MilvusContainer milvusContainer = new MilvusContainer(MilvusImage.V2_2_0); milvusContainer.start(); ``` -------------------------------- ### Start OpenFGA Container Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/openfga.md Demonstrates how to start an OpenFGA container instance using Testcontainers in Java. This is useful for integration testing with OpenFGA. ```java import org.junit.jupiter.api.Test; import org.testcontainers.containers.GenericContainer; import org.testcontainers.openfga.OpenFGAContainer; public class OpenFGAContainerTest { @Test public void container() { try (OpenFGAContainer openfga = new OpenFGAContainer(DockerImageName.parse("openfga/openfga:latest"))) { openfga.start(); // Use the OpenFGA container // For example, you can get the host and port: // String host = openfga.getHost(); // Integer port = openfga.getFirstMappedPort(); } } } ``` -------------------------------- ### Create a MockServer Container Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/mockserver.md Starts a MockServer container. This is the basic setup for using MockServer with Testcontainers. ```java MockServerContainer mockServerContainer = new MockServerContainer(DockerImageName.parse("mockserver/mockserver:mockserver-${mockserver_version}")); mockServerContainer.start(); ``` -------------------------------- ### Start Pub/Sub Emulator Container Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/gcloud.md Starts a Pub/Sub emulator container for testing. Ensure the container is properly initialized before use. ```java PubSubEmulatorContainer emulator = new PubSubEmulatorContainer(GoogleCloudImage.PUBSUB); emulator.start(); ``` -------------------------------- ### Solr Container Usage Example Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/solr.md Demonstrates how to start a Solr container instance in a Java application. This snippet requires the Solr module to be added as a project dependency. ```java import org.junit.jupiter.api.Test; import org.testcontainers.containers.SolrContainer; import org.testcontainers.utility.DockerImageName; public class SolrContainerUsage { @Test void solrContainerUsage() { try (SolrContainer solr = new SolrContainer(DockerImageName.parse("solr:8.11"))) { solr.start(); // You can now interact with Solr using solr.getSolrHostUrl() System.out.println(solr.getSolrHostUrl()); } } } ``` -------------------------------- ### Create Trino Container Instance Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/trino.md Example of how to start a Trino container instance using Testcontainers in a Java application. ```java TrinoContainer trino = new TrinoContainer("trinodb/trino:352"); trino.start(); ``` -------------------------------- ### PostgreSQL JDBC URL Example Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/jdbc.md Example of a JDBC URL for launching a PostgreSQL container with Testcontainers. ```text jdbc:tc:postgresql:9.6.8:///databasename ``` -------------------------------- ### Start Azurite container Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/azure.md Starts an Azurite storage emulator container for testing. ```java AzuriteContainer emulatorContainer = new AzuriteContainer(); emulatorContainer.start(); ``` -------------------------------- ### QuestDB JDBC URL Example Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/jdbc.md Example of a JDBC URL for launching a QuestDB container with Testcontainers. ```text jdbc:tc:questdb:6.5.3:///databasename ``` -------------------------------- ### PostGIS JDBC URL Example Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/jdbc.md Example of a JDBC URL for launching a PostGIS container with Testcontainers. ```text jdbc:tc:postgis:9.6-2.5:///databasename ``` -------------------------------- ### MySQL JDBC URL Example Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/jdbc.md Example of a JDBC URL for launching a MySQL container with Testcontainers. ```text jdbc:tc:mysql:8.0.36:///databasename ``` -------------------------------- ### Create an Nginx Container Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/nginx.md Demonstrates how to start a basic Nginx container using Testcontainers. ```java try (var nginx = new NginxContainer(DockerImageName.parse("nginx:latest"))) { nginx.start(); // You can now interact with the Nginx container } ``` -------------------------------- ### CrateDB JDBC URL Example Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/jdbc.md Example of a JDBC URL for launching a CrateDB container with Testcontainers. ```text jdbc:tc:cratedb:5.2.3:///databasename ``` -------------------------------- ### MSSQL Server JDBC URL Example Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/jdbc.md Example of a JDBC URL for launching a MSSQL Server container with Testcontainers. ```text jdbc:tc:sqlserver:2017-CU12:///databasename ``` -------------------------------- ### QuestDB Container Creation Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/questdb.md Instantiate a QuestDB container for use in Java applications. This example demonstrates basic container setup. ```java QuestDBContainer questdb = new QuestDBContainer("questdb/questdb:6.5.3"); questdb.start(); ``` -------------------------------- ### OceanBase JDBC URL Example Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/jdbc.md Example of a JDBC URL for launching an OceanBaseCE container with Testcontainers. ```text jdbc:tc:oceanbasece:4.2.1-lts:///databasename ``` -------------------------------- ### Start Default Weaviate Container Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/weaviate.md Instantiate a default Weaviate container using Java. This is the basic setup for running Weaviate with Testcontainers. ```java final WeaviateContainer weaviate = new WeaviateContainer(); weaviate.start(); ``` -------------------------------- ### Container Creation Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/timeplus.md Instantiate a Timeplus container using the Testcontainers module. This example demonstrates basic container setup. ```java import org.junit.jupiter.api.Test; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.wait.strategy.Wait; import org.testcontainers.containers.timeplus.TimeplusContainer; import org.testcontainers.utility.DockerImageName; import java.time.Duration; public class TimeplusContainerTest { @Test void container() { try (TimeplusContainer timeplus = new TimeplusContainer(DockerImageName.parse("timeplus/timeplusd:2.3.21")) .withExposedPorts(8000) .waitingFor(Wait.forHttp("/ping").withStartupTimeout(Duration.ofMinutes(5))) { // container is ready } } } ``` -------------------------------- ### Oracle JDBC URL Example Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/jdbc.md Example of a JDBC URL for launching an Oracle container with Testcontainers. ```text jdbc:tc:oracle:21-slim-faststart:///databasename ``` -------------------------------- ### Start MariaDB Container Instance Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/mariadb.md Demonstrates how to start a MySQL container instance using the Testcontainers module. This is a common pattern for integrating database testing into Java applications. ```java import org.junit.jupiter.api.Test; import org.testcontainers.containers.MariaDBContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; @Testcontainers class MariaDBContainerTest { @Container private MariaDBContainer mariaDB = new MariaDBContainer<>("mariadb:10.3.39") .withDatabaseName("test") .withUsername("test") .withPassword("test"); @Test void testSomething() { // use the container } } ``` -------------------------------- ### Start HiveMQ Enterprise Edition Container Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/hivemq.md Demonstrates how to start a HiveMQ Enterprise Edition container using Testcontainers. ```java private static final HiveMQContainer hivemq = new HiveMQContainer(DockerImageName.parse("hivemq/hivemq4")); @BeforeAll static void setUp() { hivemq.start(); } @Test void testMqtt311() throws InterruptedException, ExecutionException { // ... test logic using hivemq container } @AfterAll static void tearDown() { hivemq.stop(); } ``` -------------------------------- ### Trino JDBC URL Example Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/jdbc.md Example of a JDBC URL for launching a Trino container with Testcontainers. ```text jdbc:tc:trino:352://localhost/memory/default ``` -------------------------------- ### Start HiveMQ Community Edition Container Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/hivemq.md Demonstrates how to start a HiveMQ Community Edition container using Testcontainers. ```java private static final HiveMQContainer hivemq = new HiveMQContainer(DockerImageName.parse("hivemq/hivemq-ce")); @BeforeAll static void setUp() { hivemq.start(); } @Test void testMqtt311() throws InterruptedException, ExecutionException { // ... test logic using hivemq container } @AfterAll static void tearDown() { hivemq.stop(); } ``` -------------------------------- ### Start a Typesense Container Instance Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/typesense.md Demonstrates how to start a Typesense container instance within a Java application using Testcontainers. ```java try (var typesense = new TypesenseContainer(DockerImageName.parse("typesense/typesense:latest"))) { typesense.start(); // Use typesense container here } ``` -------------------------------- ### Start HiveMQ Container with Specific Version Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/hivemq.md Shows how to start a HiveMQ container with a specific Docker image tag. ```java private static final HiveMQContainer hivemq = new HiveMQContainer(DockerImageName.parse("hivemq/hivemq-ce:latest")); @BeforeAll static void setUp() { hivemq.start(); } @Test void testMqtt311() throws InterruptedException, ExecutionException { // ... test logic using hivemq container } @AfterAll static void tearDown() { hivemq.stop(); } ``` -------------------------------- ### Timeplus JDBC URL Example Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/jdbc.md Example of a JDBC URL for launching a Timeplus container with Testcontainers. ```text jdbc:tc:timeplus:2.3.21:///databasename ``` -------------------------------- ### DB2 JDBC URL Example Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/jdbc.md Example of a JDBC URL for launching a DB2 container with Testcontainers. ```text jdbc:tc:db2:11.5.0.0a:///databasename ``` -------------------------------- ### TimescaleDB JDBC URL Example Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/jdbc.md Example of a JDBC URL for launching a TimescaleDB container with Testcontainers. ```text jdbc:tc:timescaledb:2.1.0-pg13:///databasename ``` -------------------------------- ### MariaDB JDBC URL Example Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/jdbc.md Example of a JDBC URL for launching a MariaDB container with Testcontainers. ```text jdbc:tc:mariadb:10.3.39:///databasename ``` -------------------------------- ### Start a MongoDBContainer Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/mongodb.md Starts the previously created MongoDBContainer. Ensure the container is started before attempting to connect. ```java mongoDBContainer.start(); ``` -------------------------------- ### PGVector JDBC URL Example Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/jdbc.md Example of a JDBC URL for launching a PGVector container with Testcontainers. ```text jdbc:tc:pgvector:pg16:///databasename ``` -------------------------------- ### Start HiveMQ Container with Extension from Filesystem Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/hivemq.md Loads an extension from the filesystem into the HiveMQ container. Ensure the extension is correctly packaged. ```java try (HiveMQContainer hivemq = new HiveMQContainer(DockerImageName.parse("hivemq/hivemq-ce:latest")) .withExtension("my-extension", Path.of("src/test/resources/my-extension")) { @Override public void configure() { super.configure(); // The extension is loaded from the filesystem } }) { hivemq.start(); // ... assertions ... } ``` -------------------------------- ### ClickHouse JDBC URL Example Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/jdbc.md Example of a JDBC URL for launching a ClickHouse container with Testcontainers. ```text jdbc:tc:clickhouse:18.10.3:///databasename ``` -------------------------------- ### Starting Proxying Connections Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/toxiproxy.md Instruct the Toxiproxy container to start proxying connections to a target container. Each ToxiproxyContainer can manage multiple proxy targets. ```java Container.withNetwork("default", toxiproxy.getNetwork()); Proxy proxy = toxiproxy.getProxy("target", "target:8080"); ``` -------------------------------- ### Create ScyllaDB Container Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/scylladb.md Starts a basic ScyllaDB container instance. ```java try (ScyllaDBContainer scylladb = new ScyllaDBContainer()) { scylladb.start(); // Use the container } ``` -------------------------------- ### Create a Redis Container using JUnit 5 Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/features/creating_container.md This example demonstrates creating a Redis container within a JUnit 5 test class. The container is started before tests and destroyed after. ```java @Container private static final PostgreSQLContainer postgresql = new PostgreSQLContainer(DockerImageName.parse("postgres:15-alpine")); @Test void testSimple() { assertThat(postgresql.isRunning()).isTrue(); } ``` -------------------------------- ### Start Neo4j Enterprise Edition Container Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/neo4j.md Start a Neo4j Enterprise Edition container. This requires accepting the enterprise license terms. ```java Neo4jContainer neo4jContainer = new Neo4jContainer<>(DockerImageName.parse("neo4j:4.4-enterprise")) .withEnterpriseEdition(); neo4jContainer.start(); ``` -------------------------------- ### Start Neo4j Container Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/neo4j.md Start a Neo4j container instance. This is the basic usage for integrating Neo4j with Testcontainers. ```java Neo4jContainer neo4jContainer = new Neo4jContainer<>(DockerImageName.parse("neo4j:4.4.0")); neo4jContainer.start(); ``` -------------------------------- ### YugabyteDB JDBC URL Example Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/jdbc.md Example of a JDBC URL for launching a YugabyteDB container with Testcontainers. ```text jdbc:tc:yugabyte:2.14.4.0-b26:///databasename ``` -------------------------------- ### Start Default ActiveMQ Container Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/activemq.md Start a default ActiveMQ Classic container instance. This is useful for basic testing scenarios. ```java try (ActiveMQContainer activeMQContainer = new ActiveMQContainer()) { activeMQContainer.start(); // Use the container } ``` -------------------------------- ### Start Spanner Emulator Container Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/gcloud.md Starts a Spanner emulator container for testing. Ensure the container is properly initialized before use. ```java SpannerEmulatorContainer emulator = new SpannerEmulatorContainer(GoogleCloudImage.SPANNER); emulator.start(); ``` -------------------------------- ### Start BigQuery Emulator Container Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/gcloud.md Starts a BigQuery emulator container for testing purposes. This is typically used within a test class to provide a local BigQuery environment. ```java BigQueryEmulatorContainer bigquery = new BigQueryEmulatorContainer(GoogleCloudImage.of("gcr.io/google.com/cloudsdktool/google-cloud-cli:emulators")); bigquery.start(); ``` -------------------------------- ### Start Azure CosmosDB Emulator Container Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/azure.md Starts an Azure CosmosDB Emulator container. This container provides a local environment for developing and testing against Azure Cosmos DB. ```java final CosmosDBEmulatorContainer emulatorContainer = new CosmosDBEmulatorContainer(CosmosDBEmulatorContainer.DEFAULT_PORT); emulatorContainer.start(); ``` -------------------------------- ### Start HiveMQ Container Without Any Extensions Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/hivemq.md Starts a HiveMQ container with all pre-packaged extensions removed. This is useful if you want a clean HiveMQ instance without any default extensions. ```java try (HiveMQContainer hivemq = new HiveMQContainer(DockerImageName.parse("hivemq/hivemq-ce:latest")) .noExtensions() { @Override public void configure() { super.configure(); // No extensions are loaded } }) { hivemq.start(); // ... assertions ... } ``` -------------------------------- ### Firefox WebDriver Rule Setup Source: https://github.com/testcontainers/testcontainers-java/wiki/usage/webdriver_containers Switch to using Firefox by changing the DesiredCapabilities passed to the BrowserWebDriverContainerRule constructor. ```java new BrowserWebDriverContainerRule(DesiredCapabilities.firefox()) ``` -------------------------------- ### Start Firestore Emulator Container Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/gcloud.md Starts a Firestore emulator container for testing. This allows you to develop and test Firestore-dependent applications locally. ```java FirestoreEmulatorContainer firestore = new FirestoreEmulatorContainer(GoogleCloudImage.of("gcr.io/google.com/cloudsdktool/google-cloud-cli:emulators")); firestore.start(); ``` -------------------------------- ### Start Azure Service Bus Emulator Container Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/azure.md Starts an Azure Service Bus Emulator container. This container simulates the Azure Service Bus environment for local testing. ```java final ServiceBusEmulatorContainer emulatorContainer = new ServiceBusEmulatorContainer() .withNetwork(network) .withNetworkAliases("servicebus"); emulatorContainer.start(); ``` -------------------------------- ### Starting an Azurite container as dependency for Event Hubs Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/azure.md Starts an Azurite container to be used as a dependency for the Azure Event Hubs Emulator, typically for shared storage needs. ```java AzuriteContainer azuriteContainer = new AzuriteContainer(); azuriteContainer.withNetwork(network); azuriteContainer.start(); ``` -------------------------------- ### Start Azurite container with more accounts and keys Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/azure.md Configures an Azurite Blob container to use custom credentials with multiple accounts and keys. ```java AzuriteContainer emulatorContainer = new AzuriteContainer(AzuriteContainer.DEFAULT_IMAGE, "-k") .withCredential("account1", "key1", "key2") .withCredential("account2", "key3", "key4"); emulatorContainer.start(); ``` -------------------------------- ### Start Kibana Container with Managed Elasticsearch Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/elasticsearch.md Demonstrates starting a Kibana container that automatically connects to a managed Elasticsearch container within the same explicit network. Ensures both services can communicate. ```java try (var elasticsearch = new ElasticsearchContainer(DockerImageName.parse("elasticsearch:8.10.0"))) { var network = Network.newNetwork(); elasticsearch.withNetwork(network); elasticsearch.start(); try (var kibana = new KibanaContainer(DockerImageName.parse("kibana:8.10.0")).withNetwork(network).withElasticsearchContainer(elasticsearch)) { kibana.start(); // use the containers } } ``` -------------------------------- ### Start Azure Event Hubs Emulator container Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/azure.md Starts an Azure Event Hubs Emulator container, which can be configured with specific settings and dependencies. ```java EventHubsEmulatorContainer emulatorContainer = new EventHubsEmulatorContainer(EventHubsEmulatorContainer.DEFAULT_IMAGE) .withNetwork(network) .withNetworkAliases("eventhubs") .withConfiguration(new File("src/test/resources/eventhubs_config.json")); emulatorContainer.start(); ``` -------------------------------- ### Start ActiveMQ Container with Custom Credentials Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/activemq.md Start an ActiveMQ Classic container with custom username and password. This is necessary when the default credentials are not suitable for your tests. ```java try (ActiveMQContainer activeMQContainer = new ActiveMQContainer("apache/activemq:latest").withCredentials("user", "password")) { activeMQContainer.start(); // Use the container } ``` -------------------------------- ### Start SQL Server Container as Dependency Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/azure.md Starts a SQL Server container to be used as a dependency for the Azure Service Bus Emulator. This is useful if your tests require a SQL Server instance alongside the Service Bus Emulator. ```java final MSSQLContainer sqlContainer = new MSSQLContainer<>("mcr.microsoft.com/mssql/server:2017-latest") .withNetwork(network) .withNetworkAliases("sql"); sqlContainer.start(); ``` -------------------------------- ### Using One Shot Startup Strategy Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/features/startup_and_waits.md Use this strategy for containers that run briefly and exit. Success is determined by the container stopping with exit code 0. ```java try (GenericContainer container = new GenericContainer(DockerImageName.parse("postgres:14.5")) { container.setStartupCheckStrategy(new OneShotStartupCheckStrategy()); container.start(); // ... }) ``` -------------------------------- ### Manually Start and Stop a Generic Container Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/test_framework_integration/manual_lifecycle_control.md Use start() and stop() methods for manual lifecycle control. Implementing AutoCloseable ensures the container is stopped. ```java try (GenericContainer container = new GenericContainer("imagename")) { container.start(); // ... use the container // no need to call stop() afterwards } ``` -------------------------------- ### Pre-Testcontainers Redis Test Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/quickstart/spock_quickstart.md An example of an integration test for a Redis-backed cache that relies on a local Redis installation. ```Groovy package quickstart import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test class RedisBackedCacheIntTestStep0 extends Assertions { @Test void "should store and retrieve data from Redis"() { def redisBackedCache = new RedisBackedCache('localhost', 6379) redisBackedCache.put('key', 'value') assertEquals('value', redisBackedCache.get('key')) } } ``` -------------------------------- ### Direct Docker Hub Image Reference Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/features/image_name_substitution.md Example of a direct Docker Hub image name reference in test code. ```java String image = "mysql:8.0.36"; ``` -------------------------------- ### Create ScyllaDB Container with Custom Configuration File Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/scylladb.md Starts a ScyllaDB container with a custom configuration file. Ensure the configuration file is present in the classpath. ```java try (ScyllaDBContainer scylladb = new ScyllaDBContainer(ScyllaDBContainer.SCYLLADB_IMAGE).withConfigurationOverride("scylla.yaml")) { scylladb.start(); // Use the container } ``` -------------------------------- ### Using Minimum Duration Startup Strategy Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/features/startup_and_waits.md Ensures the container is running and has been running for a specified minimum duration. Useful for services that require a brief warm-up period. ```java try (GenericContainer container = new GenericContainer(DockerImageName.parse("postgres:14.5")) { container.setStartupCheckStrategy(new MinimumDurationStartupCheckStrategy(Duration.ofSeconds(30))); container.start(); // ... }) ``` -------------------------------- ### Create a Couchbase Cluster Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/couchbase.md Initializes and starts a Couchbase cluster using the defined container. ```java couchbaseContainer.start(); ``` -------------------------------- ### Solace Container Setup with Simple Authentication Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/solace.md Demonstrates how to set up a Solace container with basic username and password authentication. This is useful for testing applications that connect to Solace using simple credentials. ```java SolaceContainer solaceContainer = new SolaceContainer(SolaceContainer.MODULE_SOLACE_SOLACE); solaceContainer.withAdminUsername("admin").withAdminPassword("admin"); solaceContainer.start(); ``` -------------------------------- ### Starting a Vault Container Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/vault.md Instantiate a Vault container from a Java application. Ensure the Vault module is added to your project dependencies. ```java VaultContainer vaultContainer = new VaultContainer(); vaultContainer.start(); ``` -------------------------------- ### Define and Enable Reusable Container Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/features/reuse.md Define a generic container and enable the reuse feature by calling `withReuse(true)`. The container must be started manually using `start()` and not stopped automatically. ```java GenericContainer container = new GenericContainer("redis:6-alpine") .withExposedPorts(6379) .withReuse(true) ``` -------------------------------- ### Obtain Mapped Port and Host in JUnit 4 Setup Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/quickstart/junit_4_quickstart.md In your test setup method, obtain the dynamically mapped port and host address for the Redis container. Avoid hardcoding 'localhost' and use `redis.getHost()` for better portability. ```java @Before public void setUp() { String redisHost = redis.getHost(); Integer redisPort = redis.getMappedPort(6379); // Now use redisHost and redisPort to configure your component under test // e.g., cache = new RedisBackedCache(redisHost, redisPort); } ``` -------------------------------- ### Copying Files to a Container Before Startup Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/features/files.md Use MountableFile to copy files into a container before it starts. This is the recommended approach for portability across different Docker environments. ```java MountableFile.forClasspathResource("my-file.txt") ``` -------------------------------- ### Pre-Testcontainers Redis Test Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/quickstart/junit_5_quickstart.md An example of a Redis integration test written without Testcontainers, highlighting its reliance on a local Redis installation. ```java package quickstart.redis; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class RedisBackedCacheIntTestStep0 { @Test public void testSomething() { // This test is not runnable without a local Redis instance // RedisBackedCache cache = new RedisBackedCache("localhost", 6379); // cache.set("key", "value"); // assertEquals("value", cache.get("key")); } } ``` -------------------------------- ### Start Ollama Container Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/ollama.md Launches an Ollama container instance using Testcontainers for Java. ```java OllamaContainer ollama = new OllamaContainer(OllamaImageNames.LATEST); ollama.start(); ``` -------------------------------- ### Start Grafana OTel LGTM Container Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/grafana.md Instantiate a Grafana OTel LGTM container from a Java application. ```java LgtmStackContainer lgtm = new LgtmStackContainer(); lgtm.start(); ``` -------------------------------- ### Obtain Mapped Port and IP Address in Spock Setup Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/quickstart/spock_quickstart.md In the Spock test setup method, obtain the dynamically mapped port and the container's IP address to configure your component under test. Avoid hardcoding 'localhost' and use 'containerIpAddress' for better compatibility. ```Groovy def redisBackedCache def setup() { redisBackedCache = new RedisBackedCache(redis.containerIpAddress, redis.getMappedPort(6379)) redisBackedCache.put('key', 'value') } ``` -------------------------------- ### Build CqlSession for Cassandra Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/cassandra.md Builds a CqlSession to connect to the Cassandra container. Ensure the container is started before attempting to build the session. ```java try (final CqlSession cqlSession = cqlSessionBuilder().build()) { // your code here } ``` -------------------------------- ### Pre-Testcontainers JUnit 4 Test Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/quickstart/junit_4_quickstart.md An example of a JUnit 4 integration test that relies on a local Redis installation, highlighting potential reliability issues. ```java package quickstart; import org.junit.Test; import static org.junit.Assert.*; public class RedisBackedCacheIntTestStep0 { @Test public void testSomething() { // Assume RedisBackedCache is a class that interacts with a Redis instance // For this example, we'll just assert true, but in a real test, you'd instantiate // and interact with RedisBackedCache here, assuming Redis is running locally on port 6379. assertTrue(true); } } ``` -------------------------------- ### Create a PostgreSQL Container Instance Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/postgres.md Instantiate a PostgreSQL container using the PostgreSQLContainer class. This is a basic setup for running PostgreSQL in a test environment. ```java PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:15-alpine"); postgres.start(); ``` -------------------------------- ### k6 Test Script Example Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/k6.md A simple k6 test script that demonstrates accessing script variables. This script is executed by the K6 container. ```javascript export default function () { const variable = __ENV.K6_SCRIPT_VAR; console.log(`Script variable: ${variable}`); } ``` -------------------------------- ### TiDB Container Creation Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/tidb.md Start a TiDB container instance from a Java application. Ensure you have the appropriate database driver as a dependency. ```java TiDBContainer tidb = new TiDBContainer(DockerImageName.parse("pingcap/tidb:v6.1.0")); tidb.start(); ``` -------------------------------- ### OceanBase Container Definition Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/oceanbase.md Start an OceanBase container instance using Testcontainers. Ensure you have the necessary database driver dependency. ```java import org.junit.jupiter.api.Test; import org.testcontainers.containers.OceanBaseContainer; import org.testcontainers.utility.DockerImageName; public class SimpleOceanBaseCETest { @Test void testSimple() { try (OceanBaseContainer oceanbase = new OceanBaseContainer(DockerImageName.parse("oceanbase/oceanbase-ce:4.2.1-lts"))) { oceanbase.start(); // Use the container } } } ``` -------------------------------- ### R2DBC URL for PostgreSQL Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/r2dbc.md Example of an R2DBC URL to launch a PostgreSQL container. Ensure 'org.testcontainers:testcontainers-r2dbc' and the PostgreSQL module are on the classpath. ```plaintext r2dbc:tc:postgresql:///databasename?TC_IMAGE_TAG=9.6.8 ``` -------------------------------- ### Create a DockerModelRunnerContainer Instance Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/docker_model_runner.md Instantiate a DockerModelRunnerContainer to connect to the Docker Model Runner service. This is the primary way to start a proxy container for the service. ```java var dockerModelRunnerContainer = new DockerModelRunnerContainer(); dockerModelRunnerContainer.start(); ``` -------------------------------- ### Creating a GenericContainer with an ImageFromDockerfile Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/features/creating_images.md Instantiate a GenericContainer with a custom Docker image built from a Dockerfile. This example shows how to provide files and the Dockerfile itself from various sources. ```java GenericContainer container = new GenericContainer( new ImageFromDockerfile() .withFileFromString("folder/someFile.txt", "hello") .withFileFromClasspath("test.txt", "mappable-resource/test-resource.txt") .withFileFromClasspath("Dockerfile", "mappable-dockerfile/Dockerfile")) ``` -------------------------------- ### Start a MongoDBAtlasLocalContainer Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/mongodb.md Starts the MongoDBAtlasLocalContainer. This makes the MongoDB instance with Atlas Search capabilities available for testing. ```java mongoDBAtlasLocalContainer.start(); ``` -------------------------------- ### Setting up a network for Event Hubs Emulator Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/azure.md Sets up a network for the Azure Event Hubs Emulator container, ensuring proper network configuration for communication. ```java Network network = Network.newNetwork(); ``` -------------------------------- ### Querying TPCH and Memory Catalogs with Presto Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/presto.md Shows an example of creating a table in the 'memory' catalog and querying it along with the 'tpch' catalog using Presto. ```java public class SomeTest { @Rule public PrestoContainer prestoSql = new PrestoContainer(); @Test public void queryMemoryAndTpchConnectors() throws SQLException { try (Connection connection = prestoSql.createConnection(); Statement statement = connection.createStatement()) { // Prepare data statement.execute("CREATE TABLE memory.default.table_with_array AS SELECT 1 id, ARRAY[1, 42, 2, 42, 4, 42] my_array"); // Query Presto using newly created table and a builtin connector try (ResultSet resultSet = statement.executeQuery("" + "SELECT nationkey, element " + "FROM tpch.tiny.nation " + "JOIN memory.default.table_with_array twa ON nationkey = twa.id " + "LEFT JOIN UNNEST(my_array) a(element) ON true " + "ORDER BY element OFFSET 1 FETCH NEXT 3 ROWS WITH TIES ")) { List actualElements = new ArrayList<>(); while (resultSet.next()) { actualElements.add(resultSet.getInt("element")); } Assert.assertEquals(Arrays.asList(2, 4, 42, 42, 42), actualElements); } } } } ``` -------------------------------- ### Solace Container Setup with SSL Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/solace.md Shows how to configure a Solace container to use SSL for secure communication. This is essential for testing secure connections to Solace. ```java SolaceContainer solaceContainer = new SolaceContainer(SolaceContainer.MODULE_SOLACE_SOLACE); solaceContainer.withAdminUsername("admin").withAdminPassword("admin"); solaceContainer.withSslPort(5553).withTlsPort(5543); solaceContainer.start(); ``` -------------------------------- ### Create Redpanda Admin Client Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/redpanda.md Initializes an AdminClient for interacting with the Redpanda cluster's administrative APIs. Requires bootstrap server details. ```java AdminClient adminClient = redpanda.createAdminClient(); ``` -------------------------------- ### Define a Couchbase Container Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/couchbase.md Sets up a Couchbase container instance. Ensure the bucket definition is available. ```java CouchbaseContainer couchbaseContainer = new CouchbaseContainer(CouchbaseImage.COUCHBASE_7_2) .withBucket(new BucketDefinition(bucketName).withPassword(bucketPassword).withPort(bucketPort).withMemoryQuotaMB(bucketMemoryQuotaMB).withEjectionMethod(bucketEjectionMethod)); ``` -------------------------------- ### Start Bigtable Emulator Container Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/gcloud.md Starts a Bigtable emulator container for testing. This provides a local environment for Bigtable operations during development and testing. ```java BigtableEmulatorContainer bigtable = new BigtableEmulatorContainer(GoogleCloudImage.of("gcr.io/google.com/cloudsdktool/google-cloud-cli:emulators")); bigtable.start(); ``` -------------------------------- ### Start Default ActiveMQ Artemis Container Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/activemq.md Start a default ActiveMQ Artemis container instance. This is useful for basic testing scenarios with Artemis. ```java try (ArtemisContainer artemisContainer = new ArtemisContainer()) { artemisContainer.start(); // Use the container } ``` -------------------------------- ### Build CqlSession using SSL Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/scylladb.md Configures and builds a CqlSession connection to the ScyllaDB container with SSL enabled. Requires a truststore and keystore. ```java try (ScyllaDBContainer scylladb = new ScyllaDBContainer()) { scylladb.start(); SSLContext sslContext = scylladb.getSslContext(); CqlSession session = scylladb.getCqlSession(sslContext); // Use the session } ``` -------------------------------- ### Recursive File Inclusion for Dockerfile Build Context Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/features/creating_images.md This example demonstrates how to include an entire directory of files, including the Dockerfile, into the Docker build context, mimicking the behavior of 'docker build .'. ```java new GenericContainer(new ImageFromDockerfile().withRecursiveDepth(2).withFileFromClasspath("", RESOURCE_PATH)) ``` -------------------------------- ### Start HiveMQ Container with Disabled Extension Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/hivemq.md Starts a HiveMQ container with a specific extension disabled by default. This is useful for testing extension management scenarios. ```java try (HiveMQContainer hivemq = new HiveMQContainer(DockerImageName.parse("hivemq/hivemq-ce:latest")) .disableExtension("my-extension") { @Override public void configure() { super.configure(); // The extension is disabled on startup } }) { hivemq.start(); // ... assertions ... } ``` -------------------------------- ### Wait for HiveMQ Extension to Start Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/hivemq.md Configures Testcontainers to load a HiveMQ extension from a local directory and waits for a specific extension name to be started before proceeding. ```java private static final HiveMQContainer hivemq = new HiveMQContainer(DockerImageName.parse("hivemq/hivemq-ce")) .withExtension(Paths.get("src/test/resources/modifier-extension")) .waitingFor(new HiveMQExtensionSwarmReady(Duration.ofSeconds(30), "My Extension Name")); @BeforeAll static void setUp() { hivemq.start(); } @Test void testMqtt311() throws InterruptedException, ExecutionException { // ... test logic using hivemq container } @AfterAll static void tearDown() { hivemq.stop(); } ``` -------------------------------- ### Start ActiveMQ Artemis Container with Custom Credentials Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/activemq.md Start an ActiveMQ Artemis container with custom username and password. This is necessary when the default credentials are not suitable for your tests. ```java try (ArtemisContainer artemisContainer = new ArtemisContainer("apache/artemis:latest").withCredentials("user", "password")) { artemisContainer.start(); // Use the container } ``` -------------------------------- ### Start Milvus Container with External Etcd Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/milvus.md Shows how to configure a Milvus container to use an external Etcd instance. This is useful when you need to manage Etcd separately or use a pre-existing instance. ```java MilvusContainer milvusContainer = new MilvusContainer(MilvusImage.V2_2_0).withExternalEtcd("127.0.0.1:2379"); milvusContainer.start(); ``` -------------------------------- ### Create Pub/Sub Subscription in Emulator Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/gcloud.md Creates a test Pub/Sub subscription within the running emulator. This subscription can then be used for testing. ```java emulator.createSubscription("test-topic", "test-subscription"); ``` -------------------------------- ### Start ActiveMQ Artemis Container with Anonymous Login Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/activemq.md Start an ActiveMQ Artemis container that allows anonymous login. This is useful for scenarios where authentication is not required or handled externally. ```java try (ArtemisContainer artemisContainer = new ArtemisContainer("apache/artemis:latest").enableAnonymousLogin()) { artemisContainer.start(); // Use the container } ``` -------------------------------- ### PostgresContainerIT Example Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/test_framework_integration/spock.md Example of using the @Testcontainers annotation in a Spock test class to manage a Postgres container. The @Shared annotation can be used to reuse the container across tests. ```groovy import org.testcontainers.containers.PostgreSQLContainer import org.testcontainers.junit.jupiter.Container import org.testcontainers.junit.jupiter.Testcontainers import spock.lang.Shared import spock.lang.Specification @Testcontainers class PostgresContainerIT extends Specification { @Shared @Container static PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:13.3") def "should start container"() { expect: postgres.isRunning() } } ``` -------------------------------- ### Create Pub/Sub Topic in Emulator Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/gcloud.md Creates a test Pub/Sub topic within the running emulator. This is a prerequisite for creating subscriptions. ```java emulator.createTopic("test-topic"); ``` -------------------------------- ### Start HiveMQ Container Without Specific Extension Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/hivemq.md Starts a HiveMQ container with a specific pre-packaged extension, like the Kafka extension, removed. This allows fine-grained control over included extensions. ```java try (HiveMQContainer hivemq = new HiveMQContainer(DockerImageName.parse("hivemq/hivemq-ce:latest")) .noExtension("hivemq-extension-kafka") { @Override public void configure() { super.configure(); // Kafka extension is not loaded } }) { hivemq.start(); // ... assertions ... } ``` -------------------------------- ### Start Azurite container with two account keys Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/azure.md Configures an Azurite Blob container to use custom credentials with one account and two keys. ```java AzuriteContainer emulatorContainer = new AzuriteContainer(AzuriteContainer.DEFAULT_IMAGE, "-k") .withCredential("account1", "key1", "key2"); emulatorContainer.start(); ``` -------------------------------- ### Wait for First Exposed Port to Start Listening Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/features/startup_and_waits.md By default, Testcontainers waits up to 60 seconds for the first exposed network port of a container to start listening. This is a basic readiness check. ```java assertThat(container.isRunning()).isTrue(); ``` -------------------------------- ### JDBC URL with File Init Script Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/jdbc.md Load an init script from a file by prefixing the path with 'file:' in the 'TC_INITSCRIPT' parameter. The path is relative to the working directory. ```text jdbc:tc:mysql:8.0.36:///databasename?TC_INITSCRIPT=file:src/main/resources/init_mysql.sql ``` -------------------------------- ### Run Cassandra Container with Custom Configuration and Authentication Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/cassandra.md Initializes a Cassandra container with a custom cassandra.yaml file, enabling required authentication. This is useful for testing authentication mechanisms. ```java final CassandraContainer cassandraContainer = new CassandraContainer<>("cassandra:4.0.1").withConfigurationOverride("cassandra-auth-required-configuration"); cassandraContainer.start(); try (final CqlSession cqlSession = cqlSessionBuilder().build()) { // your code here } ``` -------------------------------- ### Example Image Substitutor Implementation Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/features/image_name_substitution.md A Java implementation of a custom image name substitutor, subclassing org.testcontainers.utility.ImageNameSubstitutor. This example demonstrates how to override the substitutor method to provide custom image name logic. ```java package com.mycompany.testcontainers; import org.testcontainers.utility.ImageNameSubstitutor; import org.testcontainers.utility.RegistryAuthLocator; import java.util.Optional; public class ExampleImageNameSubstitutor extends ImageNameSubstitutor { @Override public SubstitutorResult substitutor(String image, String tag) { // Example: substitute all nginx images with a specific private registry image if ("nginx".equals(image)) { return new SubstitutorResult("my.private.registry/nginx:latest", Optional.empty()); } // Example: substitute all ubuntu images with a specific private registry image and auth if ("ubuntu".equals(image)) { return new SubstitutorResult("my.private.registry/ubuntu:latest", Optional.of(RegistryAuthLocator.getRegistryAuth("my.private.registry"))); } // Fallback to default behavior return super.substitutor(image, tag); } @Override public String getDockerImageNameForTestcontainersImage(String imageName) { // Example: substitute a specific image used by Testcontainers itself if (imageName.equals("testcontainers/ryuk:0.3.3")) { return "my.private.registry/testcontainers/ryuk:0.3.3"; } return imageName; } } ``` -------------------------------- ### Basic Presto Container Usage Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/presto.md Demonstrates how to initialize and obtain the JDBC URL for a Presto container in a test class. ```java public class SomeTest { @Rule public PrestoContainer presto = new PrestoContainer(); @Test public void someTestMethod() { String url = presto.getJdbcUrl(); ... create a connection and run test as normal ``` -------------------------------- ### Example Codeinclude Block Structure Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/contributing_docs.md This is an example of how a codeinclude block is structured within markdown, using HTML tags to prevent premature rendering. It specifies a human-readable title, the relative path to the Java code file, and a targeting expression. ```markdown
<!--codeinclude-->
[Human readable title for snippet](./relative_path_to_example_code.java) targeting_expression
<!--/codeinclude-->
``` -------------------------------- ### Creating ConnectionFactoryOptions from PostgreSQL Container Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/r2dbc.md Demonstrates how to obtain ConnectionFactoryOptions from an existing PostgreSQL container instance. This is useful when you already have a container object. ```java import org.junit.jupiter.api.Test; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import io.r2dbc.spi.ConnectionFactoryOptions; import static org.assertj.core.api.Assertions.assertThat; @Testcontainers class PostgreSQLR2DBCDatabaseContainerTest { @Container static PostgreSQLContainer postgresqlContainer = new PostgreSQLContainer<>("postgres:9.6.8"); @Test void getOptions() { ConnectionFactoryOptions options = postgresqlContainer.getR2DBCConnectionFactoryOptions(); assertThat(options.get(ConnectionFactoryOptions.DRIVER)).isEqualTo("postgresql"); assertThat(options.get(ConnectionFactoryOptions.HOST)).isEqualTo("localhost"); assertThat(options.get(ConnectionFactoryOptions.PORT)).isEqualTo(postgresqlContainer.getFirstMappedPort()); assertThat(options.get(ConnectionFactoryOptions.DATABASE)).isEqualTo(postgresqlContainer.getDatabaseName()); assertThat(options.get(ConnectionFactoryOptions.USER)).isEqualTo(postgresqlContainer.getUsername()); assertThat(options.get(ConnectionFactoryOptions.PASSWORD)).isEqualTo(postgresqlContainer.getPassword()); } } ``` -------------------------------- ### Create YCQL Container Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/yugabytedb.md Example of creating a YugabyteDB container for the YCQL API. ```java final YugabyteDBContainer ysqlContainer = new YugabyteDBContainer(YugabyteDBContainer.ycqlImage()); ysqlContainer.start(); ``` -------------------------------- ### Create YSQL Container Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/yugabytedb.md Example of creating a YugabyteDB container for the YSQL API. ```java final YugabyteDBContainer ysqlContainer = new YugabyteDBContainer(YugabyteDBContainer. ysqlImage()); ysqlContainer.start(); ``` -------------------------------- ### Test with Client Against Azure CosmosDB Emulator Container Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/azure.md Demonstrates testing against the Azure CosmosDB Emulator container using a configured client. This snippet shows how to perform basic operations against the emulator. ```java client.getDatabase("my-database").createContainerIfNotExists(new ContainerProperties("my-container", "/id")); ``` -------------------------------- ### Databend Container Definition Source: https://github.com/testcontainers/testcontainers-java/blob/main/docs/modules/databases/databend.md Start a Databend container instance using Testcontainers in Java. ```java new DatabendContainer("datafuselabs/databend:v1.2.615") ```