Giriş
MongoDBContainer yaratmak için tercih edilmeyen bazı yollar şöyle
// direct implementationMongoDBContainer mongoDBContainer =
new MongoDBContainer(DockerImageName.parse("mongo:4.0.10")) //Bunu kullan// generic implementationMongoDBContainer mongoDBContainer =
new FixedHostPortGenericContainer("mongo:4.0.10"); //Bunu kullanma
Açıklaması şöyle. Yani esas sebep sabit port numarası kullanılması. Bu da testlerin paralel koşmasına mani.
Both versions should work. The difference is MongoDBContainer will run on a random port while with FixedHostPortGenericContainer you can use a port of your choosing. It simplifies connecting to Mongo a lot, cause you can enforce a good old localhost:27017 this way, so no dynamic configurations would be required.The problem with this solution is it does not work well if you have multiple tests suits using non-shared container running at once. Processes will often kill MongoDB container in their teardown phase when other suits are already running or will try to start their Mongo and find out the port is already taken.
Örnek
Şöyle yaparız
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)@Testcontainers @Import(Configuration.class) public abstract class BaseApiTest { @Container static final MongoDBContainer mongo = new MongoDBContainer("mongo:3.6-xenial"); @DynamicPropertySource static void properties(DynamicPropertyRegistry registry) { registry.add("spring.data.mongodb.uri", mongo::getReplicaSetUrl); } @TestConfiguration public static class Configuration { @Lazy @Bean("testSetupMongoClient") public MongoClient testSetupMongoClient() { return MongoClients.create(mongo.getReplicaSetUrl("test")); } } }
Örnek
Şöyle yaparız. Burada Spock kullanılıyor.
@Testcontainers@SpringBootTestclass SampleSuite extends Specification {@Sharedstatic MongoDBContainer mongoDBContainer = new MongoDBContainer("mongo:4.0.18-xenial")@DynamicPropertySourcestatic void mongoProps(DynamicPropertyRegistry registry) {mongoDBContainer.start()registry.add("spring.data.mongodb.uri", () -> mongoDBContainer.replicaSetUrl)}void cleanup() {// cleaning up a bit should be a good idea...mongoDBContainer.stop()}}
Hiç yorum yok:
Yorum Gönder