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

问题描述

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

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);
    }

} 

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

    @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 类,因为 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 文章。