在容器上的 mongoDB 运行 中创建集合和检索数据的方法

Way to create Collections and retrieve data in a mongoDB running on Container

我在应用程序的容器上有一个 MongoDB 图像 运行ning。 我想在此数据库上创建集合和文档,然后突然检索数据以测试执行 CRUD 操作的自定义存储库。 我是 JUnit 测试和容器的新手,所以我真的不知道我该怎么做。 我在网上看到有人使用 docker-compose 文件,但我直接使用 Java class 创建了 MongoDB 容器,如下例所示:

public class MongoDbContainer extends GenericContainer<MongoDbContainer> {

    
    public static final int MONGODB_PORT = 27018;
    public static final String DEFAULT_IMAGE_AND_TAG = "mongo:4.2";

    /**
     * Creates a new {@link MongoDbContainer} with the {@value DEFAULT_IMAGE_AND_TAG} image.
     * @deprecated use {@link MongoDbContainer(DockerImageName)} instead
     */
    @Deprecated
    public MongoDbContainer() {
        this(DEFAULT_IMAGE_AND_TAG);
    }

    /**
     * Creates a new {@link MongoDbContainer} with the given {@code 'image'}.
     *
     * @param image the image (e.g. {@value DEFAULT_IMAGE_AND_TAG}) to use
     * @deprecated use {@link MongoDbContainer(DockerImageName)} instead
     */
    public MongoDbContainer( String image) {
        this(DockerImageName.parse(image));
    }

    /**
     * Creates a new {@link MongoDbContainer} with the specified image.
     */
    public MongoDbContainer(final DockerImageName dockerImageName) {
        super(dockerImageName);
        addExposedPort(MONGODB_PORT);
    }

    /**
     * Returns the actual public port of the internal MongoDB port ({@value MONGODB_PORT}).
     *
     * @return the public port of this container
     * @see #getMappedPort(int)
     */
    public Integer getPort() {
        return getMappedPort(MONGODB_PORT);
    }

} 

然后我使用这个 class 在测试 class 中创建一个新对象,如下所示:

    @Testcontainers
    @SpringBootTest
    public class MongoDbContainerTest { 
    
        @Container
        static MongoDbContainer container = new MongoDbContainer(DockerImageName.parse("mongo:4.2"));

        @Test
        public void Container_Should_Be_Up() {
           assertNotNull(container);
           assertNotNull(container.getExposedPorts());      
        }
}

我不知道这是否是 运行 测试中 docker 容器的正确方法,但我想知道如何使用 Java 代码连接到此数据库.

感谢所有回答的人。

这是一个可能(推荐)的方法来使用 Testconainers 创建一个 MongoDB 数据库。

您甚至可以摆脱您的自定义 MongoDbContainer class,因为 Testcontainers 带有 dedicated Mongo module:

<dependency>
  <groupId>org.testcontainers</groupId>
  <artifactId>mongodb</artifactId>
  <scope>test</scope>
</dependency>

有多种方法可以覆盖测试的连接字符串,@DynamicPropertySource 是最方便的方法之一:

@Testcontainers
@SpringBootTest
class CustomerRepositoryTest {
 
  @Container
  static MongoDBContainer mongoDBContainer = new MongoDBContainer("mongo:4.4.2");
 
  @DynamicPropertySource
  static void setProperties(DynamicPropertyRegistry registry) {
    registry.add("spring.data.mongodb.uri", mongoDBContainer::getReplicaSetUrl);
  }

}

有关更多详细信息,请参阅这篇 MongoDB Testcontainers Setup for @DataMongoTest 文章。