Dukungan Spring Cloud Azure untuk Testcontainers

Artikel ini menjelaskan cara mengintegrasikan Spring Cloud Azure dengan Testcontainers menulis pengujian integrasi yang efektif untuk aplikasi Anda.

Testcontainer adalah framework sumber terbuka untuk menyediakan instans database, broker pesan, peramban web, atau hampir apa pun yang dapat dijalankan dalam kontainer Docker yang bersifat sementara dan ringan. Ini terintegrasi dengan JUnit, memungkinkan Anda menulis kelas pengujian yang dapat memulai kontainer sebelum salah satu pengujian dijalankan. Testcontainer sangat berguna untuk menulis pengujian integrasi yang berinteraksi dengan layanan backend sungguhan.

Pustaka spring-cloud-azure-testcontainers sekarang mendukung pengujian integrasi untuk layanan Azure berikut:

Koneksi layanan

Koneksi layanan adalah koneksi ke layanan jarak jauh apa pun. Konfigurasi otomatis Spring Boot dapat menggunakan detail koneksi layanan dan menggunakannya untuk membuat koneksi ke layanan jarak jauh. Saat melakukannya, detail koneksi lebih diutamakan daripada properti konfigurasi terkait koneksi.

Saat menggunakan Testcontainers, Anda dapat membuat detail koneksi secara otomatis untuk layanan yang berjalan dalam kontainer dengan membuat anotasi bidang kontainer di kelas pengujian.

xxxContainerConnectionDetailsFactory kelas didaftarkan dengan spring.factories. Pabrik-pabrik ini membuat kacang ConnectionDetails berdasarkan subkelas Container tertentu atau nama gambar Docker.

Tabel berikut ini menyediakan informasi tentang kelas pabrik detail koneksi yang didukung di spring-cloud-azure-testcontainers JAR:

Kelas pabrik untuk detail koneksi Biji detail koneksi
CosmosContainerConnectionDetailsFactory AzureCosmosConnectionDetails
StorageBlobContainerConnectionDetailsFactory AzureStorageBlobConnectionDetails
StorageQueueContainerConnectionDetailsFactory AzureStorageQueueConnectionDetails
EventHubsContainerConnectionDetailsFactory AzureEventHubsConnectionDetails
ServiceBusContainerConnectionDetailsFactory AzureServiceBusConnectionDetails

Siapkan dependensi

Konfigurasi berikut menyiapkan dependensi yang diperlukan:

  <properties>
    <version.spring.cloud.azure>7.4.0</version.spring.cloud.azure>
  </properties>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>com.azure.spring</groupId>
        <artifactId>spring-cloud-azure-dependencies</artifactId>
        <version>${version.spring.cloud.azure}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.testcontainers</groupId>
      <artifactId>testcontainers-junit-jupiter</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.azure.spring</groupId>
      <artifactId>spring-cloud-azure-testcontainers</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.azure.spring</groupId>
      <artifactId>spring-cloud-azure-starter-cosmos</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>

Gunakan Testcontainers

Contoh kode berikut menunjukkan penggunaan dasar Testcontainers:

@SpringBootTest(classes = CosmosTestcontainersTest.class)
@Testcontainers
@ExtendWith(SpringExtension.class)
@ImportAutoConfiguration(classes = { AzureGlobalPropertiesAutoConfiguration.class, AzureCosmosAutoConfiguration.class})
public class CosmosTestcontainersTest {

    @TempDir
    private static File tempFolder;

    @Autowired
    private CosmosClient client;

    @Container
    @ServiceConnection
    static CosmosDBEmulatorContainer cosmos = new CosmosDBEmulatorContainer(
        DockerImageName.parse("mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:latest"))
                .waitingFor(Wait.forHttps("/_explorer/emulator.pem").forStatusCode(200).allowInsecure())
                .withStartupTimeout(Duration.ofMinutes(3));

    @BeforeAll
    public static void setup() throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException {
        Path keyStoreFile = new File(tempFolder, "azure-cosmos-emulator.keystore").toPath();
        KeyStore keyStore = cosmos.buildNewKeyStore();
        try (var out = Files.newOutputStream(keyStoreFile.toFile().toPath())) {
            keyStore.store(out, cosmos.getEmulatorKey().toCharArray());
        }

        System.setProperty("javax.net.ssl.trustStore", keyStoreFile.toString());
        System.setProperty("javax.net.ssl.trustStorePassword", cosmos.getEmulatorKey());
        System.setProperty("javax.net.ssl.trustStoreType", "PKCS12");
    }

    @Test
    public void test() {
        CosmosDatabaseResponse databaseResponse = client.createDatabaseIfNotExists("Azure");
        assertThat(databaseResponse.getStatusCode()).isEqualTo(201);
        CosmosContainerResponse containerResponse = client
            .getDatabase("Azure")
            .createContainerIfNotExists("ServiceContainer", "/name");
        assertThat(containerResponse.getStatusCode()).isEqualTo(201);
    }

}

Untuk menggunakan CosmosDBEmulatorContainer, Anda perlu menyiapkan KeyStore untuk TLS/SSL. Untuk informasi selengkapnya, lihat Modul Azure Cosmos DB dalam dokumentasi Testcontainers. Dengan @ServiceConnection, konfigurasi ini memungkinkan bean terkait Cosmos DB di aplikasi untuk berkomunikasi dengan Cosmos DB yang berjalan di dalam kontainer Docker yang dikelola oleh Testcontainers. Pengaturan ini secara otomatis mendefinisikan bean AzureCosmosConnectionDetails, yang kemudian digunakan oleh konfigurasi otomatis Cosmos DB untuk mengesampingkan properti konfigurasi apa pun yang terkait dengan koneksi.

Contoh

Untuk informasi selengkapnya, lihat contohnyaspring-cloud-azure-testcontainers.