Mockito为Future返回null值

问题描述 投票:0回答:1

我在controller应用程序中对play-framework进行单元测试。

controller使用存储库,我按如下方式模拟存储库

val mockUserRepository = mock(classOf[UsersRepository])
  when(mockUserRepository.findOne(userKeys)).thenReturn(Future{Some(user)})
  when(mockUserRepository.save(user)).thenReturn(Future(Some(user)))

然后我运行以下测试。在测试中,controller.signupUser(request)调用存储库的findOne方法如下

val findUserFuture: Future[Option[User]] = userRepo.findOne(userKeys) 

        println("user future is ",findUserFuture)
        findUserFuture.flatMap { (userOption: Option[User]) => //this crashes because findUserFuture is null)

findOne返回null而不是虚拟Future{user}

"User signup request with body" should {
    "return OK and user profile if the signup profile data is correct" in {


      val jsonBody = Json.parse(
        """
          {
             "external-profile":{
                "email":"[email protected]",
                "firstname":"fn",
                "lastname":"ln",
                "password":"aA1!1111"
             }
          }
        """)
      //val jsonBody = Json.toJson(signupInfo)
      val request: Request[AnyContentAsJson] = FakeRequest("POST", "ws/users/signup",Headers(("someH"->"someV")),new AnyContentAsJson(jsonBody))
      println("sending sign up request ", request)
      //request.body = signupInfo
      val response: Future[Result] = controller.signupUser(request)
      val responseBodyAsJsValue:JsValue = contentAsJson(response)
      println("received response of sign up ", responseBodyAsJsValue)

    }
  }

错误收到个人资料

UserProfile(None,ExternalUserProfile([email protected],fn,ln,Some(aA1!1111)))
checking if the user with the following details exists LoginInfo(credentials,[email protected])
returning id 116 for name [email protected]
(user future is ,null)

java.lang.NullPointerException was thrown.
java.lang.NullPointerException
    at controllers.UserController.$anonfun$signupUser$1(UserController.scala:116)

我可能做错了什么?

mockito playframework-2.6
1个回答
0
投票

问题显然是我没有正确使用when。我读到“Mockito允许通过流畅的API配置其模拟的返回值。未指定的方法调用返回”空“值:

对象为null

数字为0

布尔值为false

集合的空集合

模拟可以根据传递给方法的参数返回不同的值。 when(...)。thenReturn(...。)方法链用于为具有预定义参数的方法调用指定返回值。 “

when期望该方法以及确切的参数。因此,如果我想调用findUser(userkey),其中userkey的值在实际调用中说1,那么我需要编写when(findUser(1))userKey=1; findUser(userKey))

在我的错误实现中,我将userkey设置为

UserKeys(1,“[email protected]”,loginInfo,“”,“”)

但是对findUser的呼吁很有价值

UserKeys(116,“d @ d.com”,loginInfo,“fn”,“ln”)

我在测试中更改了userkey值并且它工作正常

val userKeys = UserKeys(utilities.bucketIDFromEmail(email)/*returns 116*/,"[email protected]",loginInfo,"fn","ln")

      when(mockUserRepository.findOne(userKeys)).thenReturn(Future{Some(user)})
      when(mockUserRepository.save(user)).thenReturn(Future(Some(user)))
© www.soinside.com 2019 - 2024. All rights reserved.