我正在对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":"test@test.com",
"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(test@test.com,fn,ln,Some(aA1!1111)))
checking if the user with the following details exists LoginInfo(credentials,test@test.com)
returning id 116 for name test@test.com
(user future is ,null)
java.lang.NullPointerException was thrown.
java.lang.NullPointerException
at controllers.UserController.$anonfun$signupUser$1(UserController.scala:116)
我可能做错了什么?
答案 0 :(得分:0)
问题显然是我没有正确使用when
。
我读到“
Mockito允许通过流畅的API配置其模拟的返回值。未指定的方法调用返回“空”值:
对象为空
0表示数字
布尔值false
收藏的空收藏
Mocks可以根据传递给方法的参数返回不同的值。 when(....)。thenReturn(....)方法链用于为带有预定义参数的方法调用指定返回值。 “
when
需要该方法以及确切的参数。因此,如果我想在实际调用中调用findUser(userkey)
且其中userkey
的值是1
的情况,那么我需要写when(findUser(1))
或userKey=1; findUser(userKey))
。
在错误的实现中,我将userkey
设置为
UserKeys(1,“ test@test.com”,loginInfo,“”,“”)
但对findUser
的呼叫具有价值
UserKeys(116,“ d@d.com”,loginInfo,“ fn”,“ ln”)
我在测试中更改了userkey的值,并且有效
val userKeys = UserKeys(utilities.bucketIDFromEmail(email)/*returns 116*/,"d@d.com",loginInfo,"fn","ln")
when(mockUserRepository.findOne(userKeys)).thenReturn(Future{Some(user)})
when(mockUserRepository.save(user)).thenReturn(Future(Some(user)))