mongodb 测试容器中的Mongo

i86rm4rw  于 2023-05-06  发布在  Go
关注(0)|答案(2)|浏览(196)

我开始使用testcontainers,在我的旅程开始时,我遇到了一些问题(见下文)。我对mysql db做了类似的事情,效果很好。我是否错过了一些mongo特定的配置?[1][1]没有什么可做的。
提前感谢任何提示/示例。

com.mongodb.MongoSocketOpenException: Exception opening socket
at com.mongodb.internal.connection.SocketStream.open(SocketStream.java:70) ~[mongodb-driver-core-3.11.2.jar:na]
at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:128) ~[mongodb-driver-core-3.11.2.jar:na]
at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:117) ~[mongodb-driver-core-3.11.2.jar:na]
at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]

我的代码:
gradle.build

testImplementation "org.testcontainers:spock:1.14.3"
 testImplementation "org.testcontainers:mongodb:1.14.3"

application.properties

spring.data.mongodb.uri=mongodb://127.0.0.1:27017/test

测试

@Testcontainers
class TestContainersExample extends IntegrationSpec {
    @Shared
    MongoDBContainer mongoDb = new MongoDBContainer()

    def "setup"() {
        mongoDb.start()

        mongoDb.waitingFor(Wait.forListeningPort()
                .withStartupTimeout(Duration.ofSeconds(180L)));
    }

//test case
}
5f0d552i

5f0d552i1#

Testcontainers将MongoDB服务器端口Map到您机器上的随机端口。这就是为什么不能在属性文件中硬编码spring.data.mongodb.uri=mongodb://127.0.0.1:27017/test
JUnit 5和Sping Boot 〉= 2.2.6的基本设置如下所示

@Testcontainers
public class MongoDbIT {

  @Container
  public static MongoDBContainer container = new MongoDBContainer(DockerImageName.parse("mongo:5"));

  @DynamicPropertySource
  static void mongoDbProperties(DynamicPropertyRegistry registry) {
    registry.add("spring.data.mongodb.uri", container::getReplicaSetUrl);
  }

}

如果您使用的是不同的JUnit或Sping Boot 版本,请查看以下correct Testcontainers setup指南。

23c0lvtd

23c0lvtd2#

下面的完整autowired示例在Spring 6.0.X中运行良好。
它正确地绑定了yout Repository并设置了MongoClient

@DataMongoTest
@Testcontainers
public class TestContainersMongo {

    @Autowired
    UserRepository userRepository;

    @Container
    static MongoDBContainer mongoDBContainer = new MongoDBContainer(DockerImageName.parse("mongo:4.0.10"));

    @DynamicPropertySource
    static void setProperties(DynamicPropertyRegistry registry) {
        registry.add("spring.data.mongodb.uri", () -> mongoDBContainer.getReplicaSetUrl("embedded"));
    }

    @AfterEach
    void cleanUp() {
        userRepository.deleteAll();
    }

    @Test
    void shouldReturnListOfCustomerWithMatchingRate() {
        userRepository.insert(UserGenerator.generate(12));

        List<User> customers = userRepository.findAll();

        assertThat(customers).hasSize(12);
    }
}

相关问题