java - 如何在反应式 mongo 驱动程序中模拟 FindPublisher
问题描述
我正在使用 Java 中的 mongo 反应驱动程序和反应流库编写应用程序。
我有以下 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 获取多个文档的优雅方式吗?
解决方案
推荐阅读
- java - 当手机处于电源安全模式时我可以信任 MQTT
- javascript - Bootstrap-vue 输入数 Vue.js 的 MaxLength
- python - 文本中的 Reportlab 3.5 变音符号对于某些字体(Junicode)的定位错误
- spring - Spring批处理作业在应用程序启动时自动启动。如何避免身份证?
- c# - System.InvalidOperationException CrossThread 使用工作函数
- node.js - 当我尝试使用令牌获取方法时,令牌在登录后不起作用
- r - 聚合数据并在 R 中绘制条形图
- javascript - What is the problem in this recursive javascript function? [JS]
- asp.net - 如何在 ASP .NET 中使用逻辑运算符 OR“||”
- kubernetes - Rancher,Prometheus 报告双倍内存使用