Mongo in testcontainers

六眼飞鱼酱① 提交于 2020-07-23 08:03:03

问题



I started playing with testcontainers and at the beginning of my journey I faced some issue (below). I did similar thing for mysql db and it worked fine. Do I miss some mongo specific config? According to [docs][1] there is not much to do.
Thanks in advance for any tips / examples.
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]

My code:
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

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
}
  

回答1:


Testcontainers will map the MongoDB server port to a random port on your machine. That's why you can't hardcode spring.data.mongodb.uri=mongodb://127.0.0.1:27017/test in your property file.

A basic setup with JUnit 5 and Spring Boot >= 2.2.6 can look like the following

@Testcontainers
public class MongoDbIT {

  @Container
  public static MongoDBContainer mongoDBContainer = new MongoDBContainer();

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


}

If you are using a different JUnit or Spring Boot version, take a look at the following guide for the correct Testcontainers setup.



来源:https://stackoverflow.com/questions/62588809/mongo-in-testcontainers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!