问题描述
我有一个非常简单的Quarkus应用程序,该应用程序接受输入并将其使用MongoClient插入到MongoDB中。
控制器:
@ApplicationScoped
@Path("/endpoint")
public class A {
@Inject
B service;
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Document add(List<? extends Document> list) {
return service.add(list);
}
}
服务等级:
@ApplicationScoped
public class B {
@Inject
MongoClient mongoClient;
private MongoCollection<Document> getCollection() {
return mongoClient.getDatabase(dbname).getCollection(coll);
}
public Document add(List<? extends Document> list) {
Document response = new Document();
getCollection().deleteMany(new BasicDBObject());
getCollection().insertMany(list);
response.append("count",list.size());
return response;
}
}
您看到我的服务删除了现有数据并插入了新数据。对于JUnit测试,我试图设置嵌入式MongoDB,并希望我的服务调用使用嵌入式Mongo。但是没有成功。
我的JUnit类
我尝试了互联网上讨论的许多方法来设置嵌入式mongo,但没有一种方法对我有用。
我想调用我的POST服务,但实际的mongodb一定不能连接。我的JUnit类如下:
@QuarkusTest
public class test {
List<Document> request = new ArrayList<Document>();
Document doc = new Document();
doc.append("Id","007")
.append("name","Nitin");
request.add(doc);
given()
.body(request)
.header("Content-Type",MediaType.APPLICATION_JSON)
.when()
.post("/endpoint")
.then()
.statusCode(200);
}
解决方法
您需要为测试使用与常规(生产)运行不同的连接字符串。
Quakus可以使用配置文件来执行此操作,运行%test
测试时会自动选择@QuarkusTest
配置文件。
因此您可以在application.properties
中添加如下内容:
quarkus.mongodb.connection-string=mongodb://host:port
%test.quarkus.mongodb.connection-string=mongodb://localhost:27017
此处mongodb://host:port
将在应用程序的正常运行中使用,mongodb://localhost:27017
将在测试内部使用。
然后,您可以在测试过程中使用flappoodle或Testcontainers在本地主机上启动MongoDB数据库。
有关配置配置文件的更多信息:https://quarkus.io/guides/config#configuration-profiles
有关如何从Quarkus测试中启动外部服务的更多信息:https://quarkus.io/guides/getting-started-testing#quarkus-test-resource
,您是否尝试过flappedoodle:
select PatientName,PatientID,min(case when ;
_hi = 1 then ServiceDate end) as high_date,max(score) as high_score,min(case when seqnum_lo = 1 then ServiceDate end) as low_date,min(score) as low_score
from (select t.*
row_number() over (partition by PatientID order by Score desc,ServiceDate asc) as seqnum_hi,row_number() over (partition by PatientID order by Score,ServiceDate desc) as seqnum_lo
from t
) t
group by PatientName,PatientID;
参考:Embedded MongoDB when running integration tests
,感谢大家的建议。我在application.properties文件中声明了测试集合。当我们运行junit时,会自动激活%test配置文件,因此我的服务会自动选择测试集合。我的junit测试用例完成后,我删除了测试集合。