[ Web Proxy ]
URL:
Viewing: https://java.testcontainers.org/supported_docker_environment/../../modules/azure/ [Back]  [Original]

Azure Module - Testcontainers for Java
Skip to content
Testcontainers [Testcontainers] Menu
testcontainers-java
Content

Azure Module

Note

This module is INCUBATING. While it is ready for use and operational in the current version of Testcontainers, it is possible that it may receive breaking changes in the future. See our contributing guidelines for more information on our incubating modules policy.

Testcontainers module for the Microsoft Azure's SDK.

Currently, the module supports Azurite, Azure Event Hubs, Azure Service Bus and CosmosDB emulators. In order to use them, you should use the following classes:

Class Container Image
AzuriteContainer mcr.microsoft.com/azure-storage/azurite
EventHubsEmulatorContainer mcr.microsoft.com/azure-messaging/eventhubs-emulator
ServiceBusEmulatorContainer mcr.microsoft.com/azure-messaging/servicebus-emulator
CosmosDBEmulatorContainer mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator

Usage example

Azurite Storage Emulator

Start Azurite Emulator during a test:

Starting an Azurite container
AzuriteContainer emulator = new AzuriteContainer("mcr.microsoft.com/azure-storage/azurite:3.33.0")

Note

SSL configuration is possible using the withSsl(MountableFile, String) and withSsl(MountableFile, MountableFile) methods.

Newer Azure Storage SDK versions can send API versions that Azurite does not support. Use withCommandOptions(...) to append extra Azurite flags such as --skipApiVersionCheck. AzuriteContainer rebuilds its process command in configure(), so .withCommand(...) cannot be used for extra flags.

Pass extra Azurite command options
AzuriteContainer emulator = new AzuriteContainer("mcr.microsoft.com/azure-storage/azurite:3.33.0")
    .withCommandOptions("--skipApiVersionCheck");

If the tested application needs to use more than one set of credentials, the container can be configured to use custom credentials. Please see some examples below.

Starting an Azurite Blob container with one account and two keys
AzuriteContainer emulator = new AzuriteContainer("mcr.microsoft.com/azure-storage/azurite:3.33.0")
    .withEnv("AZURITE_ACCOUNTS", "account1:key1:key2")
Starting an Azurite Blob container with more accounts and keys
AzuriteContainer emulator = new AzuriteContainer("mcr.microsoft.com/azure-storage/azurite:3.33.0")
    .withEnv("AZURITE_ACCOUNTS", "account1:key1;account2:key2")

Using with Blob

Build Azure Blob client:

Build Azure Blob Service client
BlobServiceClient blobServiceClient = new BlobServiceClientBuilder()
    .connectionString(container.getConnectionString())
    .buildClient();

In case the application needs to use custom credentials, we can obtain them with a different method:

Obtain connection string with non-default credentials
String connectionString1 = emulator.getConnectionString("account1", "key1");
// the second account will not have access to the same container
String connectionString2 = emulator.getConnectionString("account2", "key2");

Using with Queue

Build Azure Queue client:

Build Azure Queue Service client
QueueServiceClient queueServiceClient = new QueueServiceClientBuilder()
    .connectionString(container.getConnectionString())
    .buildClient();

Note

We can use custom credentials the same way as defined in the Blob section.

Using with Table

Build Azure Table client:

Build Azure Table Service client
TableServiceClient tableServiceClient = new TableServiceClientBuilder()
    .connectionString(container.getConnectionString())
    .buildClient();

Note

We can use custom credentials the same way as defined in the Blob section.

Azure Event Hubs Emulator

Configuring the Azure Event Hubs Emulator container
{
    "UserConfig": {
        "NamespaceConfig": [
            {
                "Type": "EventHub",
                "Name": "emulatorNs1",
                "Entities": [
                    {
                        "Name": "eh1",
                        "PartitionCount": "1",
                        "ConsumerGroups": [
                            {
                                "Name": "cg1"
                            }
                        ]
                    }
                ]
            }
        ],
        "LoggingConfig": {
            "Type": "File"
        }
    }
}

Start Azure Event Hubs Emulator during a test:

Setting up a network
Network network = Network.newNetwork();
Starting an Azurite container as dependency
AzuriteContainer azuriteContainer = new AzuriteContainer("mcr.microsoft.com/azure-storage/azurite:3.33.0")
    .withNetwork(network);
Starting an Azure Event Hubs Emulator container
EventHubsEmulatorContainer emulator = new EventHubsEmulatorContainer(
    "mcr.microsoft.com/azure-messaging/eventhubs-emulator:2.0.1"
)
    .acceptLicense()
    .withNetwork(network)
    .withConfig(MountableFile.forClasspathResource("/eventhubs_config.json"))
    .withAzuriteContainer(azuriteContainer);

Using Azure Event Hubs clients

Configure the consumer and the producer clients:

Configuring the clients
EventHubProducerClient producer = new EventHubClientBuilder()
    .connectionString(emulator.getConnectionString())
    .fullyQualifiedNamespace("emulatorNs1")
    .eventHubName("eh1")
    .buildProducerClient();
EventHubConsumerClient consumer = new EventHubClientBuilder()
    .connectionString(emulator.getConnectionString())
    .fullyQualifiedNamespace("emulatorNs1")
    .eventHubName("eh1")
    .consumerGroup("cg1")
    .buildConsumerClient();

Azure Service Bus Emulator

Configuring the Azure Service Bus Emulator container
{
    "UserConfig": {
        "Namespaces": [
            {
                "Name": "sbemulatorns",
                "Queues": [
                    {
                        "Name": "queue.1",
                        "Properties": {
                            "DeadLetteringOnMessageExpiration": false,
                            "DefaultMessageTimeToLive": "PT1H",
                            "DuplicateDetectionHistoryTimeWindow": "PT20S",
                            "ForwardDeadLetteredMessagesTo": "",
                            "ForwardTo": "",
                            "LockDuration": "PT1M",
                            "MaxDeliveryCount": 3,
                            "RequiresDuplicateDetection": false,
                            "RequiresSession": false
                        }
                    }
                ],
                "Topics": []
            }
        ],
        "Logging": {
            "Type": "File"
        }
    }
}

Start Azure Service Bus Emulator during a test:

Setting up a network
Network network = Network.newNetwork();
Starting a SQL Server container as dependency
MSSQLServerContainer mssqlServerContainer = new MSSQLServerContainer(
    "mcr.microsoft.com/mssql/server:2022-CU14-ubuntu-22.04"
)
    .acceptLicense()
    .withPassword("yourStrong(!)Password")
    .withCreateContainerCmdModifier(cmd -> {
        cmd.getHostConfig().withCapAdd(Capability.SYS_PTRACE);
    })
    .withNetwork(network);
Starting a Service Bus Emulator container
ServiceBusEmulatorContainer emulator = new ServiceBusEmulatorContainer(
    "mcr.microsoft.com/azure-messaging/servicebus-emulator:1.1.2"
)
    .acceptLicense()
    .withConfig(MountableFile.forClasspathResource("/service-bus-config.json"))
    .withNetwork(network)
    .withMsSqlServerContainer(mssqlServerContainer);

Using Azure Service Bus clients

Configure the sender and the processor clients:

Configuring the sender client
ServiceBusSenderClient senderClient = new ServiceBusClientBuilder()
    .connectionString(emulator.getConnectionString())
    .sender()
    .queueName("queue.1")
    .buildClient();
Configuring the processor client
ServiceBusProcessorClient processorClient = new ServiceBusClientBuilder()
    .connectionString(emulator.getConnectionString())
    .processor()
    .queueName("queue.1")
    .processMessage(messageConsumer)
    .processError(errorConsumer)
    .buildProcessorClient();

CosmosDB

Start Azure CosmosDB Emulator during a test:

Starting an Azure CosmosDB Emulator container
CosmosDBEmulatorContainer emulator = new CosmosDBEmulatorContainer(
    DockerImageName.parse("mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:latest")
);

Prepare KeyStore to use for SSL.

Building KeyStore from certificate within container
Path keyStoreFile = tempFolder.resolve("azure-cosmos-emulator.keystore");
KeyStore keyStore = emulator.buildNewKeyStore();
keyStore.store(new FileOutputStream(keyStoreFile.toFile()), emulator.getEmulatorKey().toCharArray());

Set system trust-store parameters to use already built KeyStore:

Set system trust-store parameters
System.setProperty("javax.net.ssl.trustStore", keyStoreFile.toString());
System.setProperty("javax.net.ssl.trustStorePassword", emulator.getEmulatorKey());
System.setProperty("javax.net.ssl.trustStoreType", "PKCS12");

Build Azure CosmosDB client:

Build Azure CosmosDB client
CosmosAsyncClient client = new CosmosClientBuilder()
    .gatewayMode()
    .endpointDiscoveryEnabled(false)
    .endpoint(emulator.getEmulatorEndpoint())
    .key(emulator.getEmulatorKey())
    .buildAsyncClient();

Test against the Emulator:

Testing against Azure CosmosDB Emulator container
CosmosDatabaseResponse databaseResponse = client.createDatabaseIfNotExists("Azure").block();
assertThat(databaseResponse.getStatusCode()).isEqualTo(201);
CosmosContainerResponse containerResponse = client
    .getDatabase("Azure")
    .createContainerIfNotExists("ServiceContainer", "/name")
    .block();
assertThat(containerResponse.getStatusCode()).isEqualTo(201);

Adding this module to your project dependencies

Add the following dependency to your pom.xml/build.gradle file:

GradleMaven
testImplementation "org.testcontainers:testcontainers-azure:2.0.5"
<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>testcontainers-azure</artifactId>
    <version>2.0.5</version>
    <scope>test</scope>
</dependency>

Web Proxy Viewer  |  New URL  |  Original Page