Mongo in testcontainers

Viewed 8227

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 Answers

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 container = new MongoDBContainer(DockerImageName.parse("mongo:5"));

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


}

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

Related