尝试使用junit 5和micronaut设置TestMongodbContainer,而不是在测试环境的随机端口上启动mongodb,它使用的是application.yml配置。
应用程序.yml
micronaut:
application:
name: feteBirdProductConsumer
mongodb:
uri: "mongodb://${MONGO_HOST:localhost}:${MONGO_PORT:27017}"
database: "FeteBird-Product"
junit测试
@MicronautTest
@Testcontainers
public class ProductListenerTest {
private final IProductProducer iProductProducer;
@Container
private final MongoDBContainer mongoDBContainer = new MongoDBContainer(DockerImageName.parse("mongo:4.0.10"));
public ProductListenerTest(IProductProducer iProductProducer) {
this.iProductProducer = iProductProducer;
}
@BeforeEach
@DisplayName("Mongo Db container starting")
void mongoDbContainerStarting() {
mongoDBContainer.start();
}
@Test
@DisplayName("Check if Mongo db container is up")
void checkIfMongoDbContainerIsUp() {
Assertions.assertTrue(mongoDBContainer.isRunning());
}
@Test
@DisplayName("Should search based on the name")
void shouldSearchBasedOnTheName() {
iProductProducer.findFreeText("string").subscribe(item -> {
System.out.println(item);
});
}
}
在 shouldSearchBasedOnTheName
方法返回值来自application.yml mongodb config。
在测试环境中,我没有向mongodb插入任何值,但是该方法已经从应用程序mongodb返回了值
我想我缺少mongodb的配置,但不知道如何设置
更新
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class ProductListenerTest implements TestPropertyProvider {
@Nonnull
@Override
public Map<String, String> getProperties() {
mongoDBContainer.start();
String address = mongoDBContainer.getHost();
Integer port = mongoDBContainer.getFirstMappedPort();
return CollectionUtils.mapOf(
"MONGO_HOST", address,
"MONGO_PORT", port
);
}
}
例外
com.mongodb.MongoSocketReadException: Prematurely reached end of stream
暂无答案!
目前还没有任何答案,快来回答吧!