我正在使用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