我正在使用Junit 5动态测试。 我的目的是从集合中创建一个元素流,并将其传递给JUnit5进行测试。 但是,通过此代码,我只能运行1000条记录。我如何使这个工作无缝地无阻塞。从集合中创建元素流
MongoCollection<Document> collection = mydatabase.getCollection("mycoll");
final List<Document> cache = Collections.synchronizedList(new ArrayList<Document>());
FindIterable<Document> f = collection.find().batchSize(1000);
f.batchCursor(new SingleResultCallback<AsyncBatchCursor<Document>>() {
@Override
public void onResult(AsyncBatchCursor<Document> t, Throwable thrwbl) {
t.next(new SingleResultCallback<List<Document>>() {
@Override
public void onResult(List<Document> t, Throwable thrwbl) {
if (thrwbl != null) {
th.set(thrwbl);
}
cache.addAll(t);
latch.countDown();;
}
});
}
});
latch.await();
return cache.stream().map(batch->process(batch));
更新的代码
@ParameterizedTest
@MethodSource("setUp")
void cacheTest(MyClazz myclass) throws Exception {
assertTrue(doTest(myclass));
}
public static MongoClient getMongoClient() {
// get client here
}
private static Stream<MyClazz> setUp() throws Exception {
MongoDatabase mydatabase = getMongoClient().getDatabase("test");
List<Throwable> failures = new ArrayList<>();
CountDownLatch latch = new CountDownLatch(1);
List<MyClazz> list = Collections.synchronizedList(new ArrayList<>());
mydatabase.getCollection("testcollection").find()
.toObservable().subscribe(
document -> {
list.add(process(document));
},
throwable -> {
failures.add(throwable);
},
() -> {
latch.countDown();
});
latch.await();
return list.stream();
}
public boolean doTest(MyClazz myclass) {
// processing goes here
}
public MyClazz process(Document doc) {
// doc gets converted to MyClazz
return MyClazz;
}
即使是现在,我看到它的单元测试发生后,所有的数据被加载。 我认为这是因为latch.await()。但是,如果我删除它,则有可能没有运行测试用例,因为db可能正在加载集合。
我的用例是:我有mongo中的百万条记录,并且正在运行它们的集成测试用例。将所有内容加载到内存中是不可行的,因此我正在尝试流式传输解决方案。
非常感谢。但我不认为我可以立即调用doTest,因为这些是动态测试。我需要能够创建一个mongo数据库结果流并返回它们。有没有办法我可以做到这一点?如果对我的用例有不同的解决方案,我很好。最难的部分似乎是批量动态测试。我确信有一种方法,就是我不知道。 – user3044440
这里听起来可能有些混乱。我的答案**中的代码确实**“创建mongo数据库结果流”。如果您在返回批次之前选择批量处理,则不再进行流式处理。或者换句话说,如果我的答案中的代码不符合您的目的,那么您实际上并不需要MongoDB结果流。 – glytching
我同意你提供的代码确实创建了mongo结果流。它不会与我正在写的junit和那种用例有关。我想知道是否有我的用例的解决方案,因此正在考虑配料 – user3044440