AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。

テストコンテナを使用したJavaとMongoDBによる統合テスト

Testcontainers は、統合テストを簡素化するためにDockerコンテナを使用するJavaライブラリです。テスト中に実行される一時的なデータベースインスタンスを作成し、テストが終了すると自動的に除きます。

このチュートリアルでは、標準Javaとアプリケーションの両方でMongoDBとTestcontainersを使用する方法を説明します。

統合テストは、アプリケーションのさまざまな部分がどのように連携するかをチェックします。個々のコード部分を検証するユニットテストとは異なり、統合テストは、コードがデータベースやAPIなどの外部システムと正しく交流することを確認します。

テストコンテナは、テストを実行中ときに次の手順を実行します。

  1. テストの前:コンテナを作成し、データベースをロードし、 コレクションを作成します

  2. テスト中: テストコードを実行します

  3. テスト後: コンテナを除き、リソースを解放します

Testcontainer を使用するテストは、どのコンピューターやオペレーティング システムでも同じ方法で実行し、各テストは独自のデータベースインスタンスを使用します。必要に応じて、異なるデータベースのバージョンを切り替えることもできます。

始める前に、以下をインストールしてください。

また、アプリケーションの pom.xmlファイルには次の依存関係も追加する必要があります。

<dependencyManagement> <dependencies> <!-- MongoDB Java Driver BOM --> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-bom</artifactId> <type>pom</type> <scope>import</scope> </dependency> <!-- Testcontainers BOM --> <dependency> <groupId>org.testcontainers</groupId> <artifactId>testcontainers-bom</artifactId> <type>pom</type> <scope>import</scope> </dependency> <!-- JUnit BOM --> <dependency> <groupId>org.junit</groupId> <artifactId>junit-bom</artifactId> <type>pom</type> <scope>import</scope> </dependency> </dependencies></dependencyManagement>

次の例では、 IMDb の評価が 7.0 を超える映画を検索するクエリをテストしています。完全なコードを表示するには、GitHubリポジトリを参照してください。

1

次のコードでは、MongoDBコンテナが作成されます。@Container アノテーションにより、テストの前にコンテナが起動され、テストの完了後にコンテナが停止します。

@Containerprivate static final MongoDBContainer mongoDBContainer = new MongoDBContainer("mongo:7.0.0");
2

次のコードはコンテナに接続し、サンプル映画を追加します。

@BeforeAllpublic void setup() { String uri = mongoDBContainer.getConnectionString(); mongoClient = MongoClients.create(uri); database = mongoClient.getDatabase("testdb"); collection = database.getCollection("testCollection"); // Insert sample data Document doc1 = new Document("title", "Inception").append("imdb", new Document("rating", 8.8)); Document doc2 = new Document("title", "The Room").append("imdb", new Document("rating", 3.7)); Document doc3 = new Document("title", "The Dark Knight").append("imdb", new Document("rating", 9.0)); collection.insertMany(List.of(doc1, doc2, doc3));}
3

次のコードでは、imdb.ratingフィールドの値が 7 より大きい映画に対してクエリを実行し、結果を確認します。

@Testvoid testMoviesWithHighRating() { List<Document> resultDocuments = new ArrayList<>(); try (MongoCursor<Document> cursor = collection.find(Filters.gt("imdb.rating", 7)) .projection(new Document("title", 1).append("_id", 0)) .iterator()) { while (cursor.hasNext()) { Document doc = cursor.next(); System.out.println(doc.toJson()); resultDocuments.add(doc); } } assertEquals(2, resultDocuments.size()); for (Document doc : resultDocuments) { assertTrue(doc.containsKey("title")); assertFalse(doc.containsKey("_id")); }}

このテストでは、次の項目を確認します。

  • クエリは完全に 2 ドキュメントを返します

  • 各ドキュメントには titleフィールドがあります

  • 各ドキュメントには _idフィールドが除外されます

次の例では、spring Upstart MongoDB Aggregationsリポジトリ のコードを使用して findAll() メソッドをテストします。

1

次のコードでは、MongoDBコンテナを作成します。

@Containerpublic static MongoDBContainer mongoDBContainer = new MongoDBContainer(DockerImageName.parse("mongo:7.0.0"));
2

次のコードでは、テストデータベースを使用するようにspringが起動するように構成します。

@DynamicPropertySourcestatic void setProperties(DynamicPropertyRegistry registry) { registry.add("spring.data.mongodb.uri", mongoDBContainer::getReplicaSetUrl); registry.add("spring.data.mongodb.database", () -> "testdb");} @BeforeAllpublic static void setUpAll() { String mongoUri = mongoDBContainer.getConnectionString(); mongoClient = MongoClients.create(mongoUri);} @BeforeEachpublic void setUp() { salesRepository.save(createMockSales());} private Sales createMockSales() { Item item1 = new Item("Item1", Arrays.asList("Tag1", "Tag2"), new BigDecimal("19.99"), 2); Item item2 = new Item("Item2", Arrays.asList("Tag3", "Tag4"), new BigDecimal("29.99"), 1); List<Item> items = Arrays.asList(item1, item2); Customer customer = new Customer("Male", 30, "customer@example.com", 5); return new Sales(new ObjectId(), new Date(), items, "Store1", customer, true, "Online");}
3

次のコードは、findAll() メソッドをテストします。

@Testpublic void testFindAll() { List<Sales> salesList = salesRepository.findAll(); assertThat(salesList).isNotEmpty(); assertThat(salesList.size()).isEqualTo(1); Sales sales = salesList.get(0); assertThat(sales.getStoreLocation()).isEqualTo("Store1"); assertThat(sales.getCustomer().getEmail()).isEqualTo("customer@example.com"); assertThat(sales.getItems()).hasSize(2);}

このテストでは、次の項目を確認します。

  • クエリは完全に 2 ドキュメントを返します

  • 各ドキュメントには titleフィールドがあります

  • 各ドキュメントには _idフィールドが除外されます