你如何模拟将使用地图功能的未来?

时间:2015-04-23 19:00:42

标签: scala mockito couchbase future specs2

我正在尝试对以下的沙发基础方法调用进行单元测试,我在这里找不到满意的样本,所以我想我发布了一个问题...... / p>

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"$token\uefff"))
      .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]]的所有层次。谢谢你的时间!

1 个答案:

答案 0 :(得分:5)

我想我可能已经找到了如何使用地图操作模拟未来工作的答案。好像我们创造了一个成功的'未来,它将如下工作:

  val mockUserSession = createTestUserSession
  val mockUserSessionList = mock[List[UserSession]]
  val mockUserSessionListFuture = Future.successful[List[UserSession]](mockUserSessionList)

  mockUserSessionList.headOption returns Some(mockUserSession)

这将允许getUserSession中的地图提供headOption的正确实例,在这种情况下为Some(mockUserSession)