我正在使用Java中的mongo反应式驱动程序和reactstreams库编写应用程序。
我有以下DAO代码:
@Override
public Flux<ContentVersion> findBySearch(String appKey,ContentVersionSearchRequest request,Pager pager) {
final var searchResultsPublisher = mongoClient.getDatabase(appKey)
.getcollection(COLLECTION_CONTENT_VERSION,ContentVersion.class)
.find(prepareSearchFilter(request))
.sort(orderBy(ascending(FIELD_VERSION_STATUS_ORDER),descending(FIELD_UPDATE_DATE)))
.skip(pager.getSkip())
.limit(pager.getMax());
return Flux.from(searchResultsPublisher);
}
在junit测试中,我模拟了MongoClient,MongoDatabase,MongoCollection,但最终MongoCollection返回了FindPublisher,我不知道如何正确模拟它。
我已经通过如下模拟订阅方法成功编写了单元测试。但是,这对我来说似乎不正确。
@Mock
private MongoClient mongoClient;
@Mock
private MongoDatabase database;
@Mock
private MongoCollection<ContentVersion> collection;
@Mock
private FindPublisher<ContentVersion> findPublisher;
@Mock
private UpdateResult updateResult;
@InjectMocks
private ContentVersionDaoImpl contentVersionDao;
@BeforeEach
void initCommonmocks() {
when(mongoClient.getDatabase("ddpApp")).thenReturn(database);
when(database.getcollection(MongoConstants.COLLECTION_CONTENT_VERSION,ContentVersion.class)).thenReturn(collection);
when(collection.find(any(Bson.class))).thenReturn(findPublisher);
when(collection.find(any(Document.class))).thenReturn(findPublisher);
when(findPublisher.limit(anyInt())).thenReturn(findPublisher);
when(findPublisher.skip(anyInt())).thenReturn(findPublisher);
when(findPublisher.sort(any())).thenReturn(findPublisher);
}
@Test
void shouldFindBySearch() {
final var contentVersion1 = new ContentVersion();
final var contentVersion2 = new ContentVersion();
final var testPublisher = TestPublisher.<ContentVersion>createCold()
.emit(contentVersion1,contentVersion2);
doAnswer(invocation -> {
testPublisher.subscribe(invocation.getargument(0,Subscriber.class));
return null;
}).when(findPublisher).subscribe(any());
final var searchFlux = contentVersionDao
.findBySearch("ddpApp",new ContentVersionSearchRequest(null,null,null),new Pager(1,10));
StepVerifier.create(searchFlux)
.expectNext(contentVersion1)
.expectNext(contentVersion2)
.expectComplete()
.verify();
}
有人知道编写junit测试来测试从mongodb获取多个文档的优雅方法吗?