I am trying to test the Micronaut application using MongoDb and RabbitMQ test containers. The application.yml
has the below configuration
mongodb:
uri: "mongodb://${MONGO_HOST:localhost}:${MONGO_PORT:27017}"
database: "FeteBird-Product"
I have the below code for the configuration
@Introspected
@ConfigurationProperties("mongodb")
public record MongodbConfiguration(@NotNull String uri, @NotNull String database) {
}
In the repository. The repository is in another project
@Singleton
public record Repository(MongoClient mongoClient, MongodbConfiguration mongodbConfiguration) implements IRepository {
@Override
public <T> MongoCollection<T> getCollection(String collectionName, Class<T> typeParameterClass) {
return mongoClient
.getDatabase(mongodbConfiguration.database())
.getCollection(collectionName, typeParameterClass);
}
}
mongodbConfiguration.uri
is always mongodb://localhost:27017
, however in the JUnit testing I have the below code
@Testcontainers
public abstract class TestContainerFixture {
public static final GenericContainer mongoDBContainer;
public static final GenericContainer rabbitMQContainer;
static {
mongoDBContainer = new GenericContainer(DockerImageName.parse("mongo:4.0.10")).withExposedPorts(27017);
rabbitMQContainer = new GenericContainer(DockerImageName.parse("rabbitmq:3-management-alpine")).withExposedPorts(5672);
mongoDBContainer.start();
rabbitMQContainer.start();
}
}
@MicronautTest
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class DiscountDeleteListenerTest extends TestContainerFixture {
private ApplicationContext applicationContext;
@BeforeAll
@DisplayName("Initial application setup")
void initialApplicationSetup() {
applicationContext = ApplicationContext.run(
Map.of("mongodb.uri",
String.format("mongodb://%s:%s", mongoDBContainer.getContainerIpAddress(), mongoDBContainer.getMappedPort(27017)),
"rabbitmq.uri",
String.format("amqp://%s:%s", rabbitMQContainer.getContainerIpAddress(), rabbitMQContainer.getMappedPort(5672)))
, "test"
);
iDiscountProducer = applicationContext.getBean(IDiscountProducer.class);
}
}
The below code is fine
String.format("mongodb://%s:%s", mongoDBContainer.getContainerIpAddress(), mongoDBContainer.getMappedPort(27017))
This gives the URL as mongodb://localhost:57032
Now when I finish all the unit tests and check the database it is inserting, updating, and deleting from the local docker instance that is port 27017
The host for the cluster is still pointing to 27017
Got some idea from here https://github.com/micronaut-projects/micronaut-test/issues/32 but still quite not sure how to do it.