【发布时间】:2017-09-12 23:02:39
【问题描述】:
我正在使用 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()。但是,如果我删除它,则可能不会运行任何测试用例,因为数据库可能正在加载集合。
我的用例是:我在 mongo 中有数百万条记录,并且正在使用它们运行某种集成测试用例。将它们全部加载到内存中是不可行的,因此我正在尝试流式解决方案。
【问题讨论】:
标签: java mongodb unit-testing junit5 mongodb-asyc-driver