我正在尝试为以下 couchbase 方法调用进行单元测试,我在 SO 中找不到令人满意的示例,所以我想我会发布一个问题......
def getUserSession(token: String, ipAddr: String, userAgent: Option[String]): Future[Option[UserSession]] = {
val query = new Query().setIncludeDocs(true).setLimit(1)
.setRangeStart(ComplexKey.of(token))
.setRangeEnd(ComplexKey.of(s"$tokenuefff"))
.setStale(Stale.FALSE)
bucket.find[UserSession](DOC_NAME, VIEW_BY_TOKEN)(query).map(_.headOption) map {
userSessionOpt => {
userSessionOpt filter {
userSession =>
(userSession.ipAddr == ipAddr) &&
(!userAgent.isDefined || !userSession.userAgent.isDefined || userSession.userAgent == userAgent)
}
}
}
}
所以这是我的尝试,我的单元测试摘录:
val mockQueryResult = mock[Future[List[UserSession]]]
val mockUserSessionList = mock[List[UserSession]]
val mockUserSession = mock[UserSession]
// This is just my trial and erros
mockUserSessionList.head returns mockUserSession
mockUserSessionList(0) returns mockUserSession
Await.result(mockQueryResult, Duration(60, SECONDS)) returns mockUserSessionList
mockBucket.find[UserSession](any[String], any[String])(any[Query])(any[Reads[UserSession]], any[ExecutionContext]) returns mockQueryResult
val queryCaptor = capture[Query]
val readsCaptor = capture[Reads[UserSession]]
val executionContextCaptor = capture[ExecutionContext]
val docNameCaptor = capture[String]
val viewNameCaptor = capture[String]
userSessionRepositoryWithMockBucket.getUserSession(TEST_SESSION_TOKEN1, TEST_IP_ADDR1, TEST_USER_AGENT)
there was one(mockBucket).find[UserSession](docNameCaptor, viewNameCaptor)(queryCaptor)(readsCaptor, executionContextCaptor)
现在,在bucket.find
方法调用的某个时刻会抛出 NPE。我做了一些挖掘,似乎Await.result
回报嘲笑在返回值方面并没有真正起作用,map
可能是出于明显的原因。如果我修改了我的 getUserSession 函数以使用 Await.result
,它确实会返回结果。我只是在尝试一下,因为我还没有创造性地想出其他方法(这对我来说是新的)。
似乎有一种不那么冗长的方法来进行模拟,而不必做所有层次的Future[List[UserSession]]
。谢谢你的时间!
我想我可能已经找到了如何模拟地图操作的未来问题的答案。似乎如果我们创造一个"成功"的未来,它将按如下方式工作:
val mockUserSession = createTestUserSession
val mockUserSessionList = mock[List[UserSession]]
val mockUserSessionListFuture = Future.successful[List[UserSession]](mockUserSessionList)
mockUserSessionList.headOption returns Some(mockUserSession)
这反过来又允许在getUserSession
中为地图提供正确的headOption
实例,在这种情况下Some(mockUserSession)