【发布时间】:2019-03-31 18:30:38
【问题描述】:
我写了这个函数,当用户点击一个链接时会调用它。该函数基本上创建了一个更改了一个字段的用户数据副本(从而保持原始值不变,即不可变),然后用新值更新数据库
def confirmSignupforUser(user:User):Future[Option[User]] = {
println("confirming user: "+user)
val newInternalProfile = user.profile.internalProfileDetails.get.copy(confirmed=true)//new data which should be added in the database
println("old internal profile: "+user.profile.internalProfileDetails.get)
println("new internal profile: "+newInternalProfile)
val newProfile = UserProfile(Some(newInternalProfile),user.profile.externalProfileDetails)
println("old profile: "+user.profile)
println("new profile: "+newProfile)
val confirmedUser = user.copy(profile=newProfile)
for(userOption <- userRepo.update(confirmedUser)) yield { //database operation
println("returning modified user:"+userOption)
userOption
}
}
为了测试代码,我编写了以下规范
"confirmSignupforUser" should {
"change confirmed status to True" in {
val testEnv = new TestEnv(components.configuration)
val externalProfile = testEnv.externalUserProfile
val internalUnconfirmedProfile = InternalUserProfile(testEnv.loginInfo,1,false,None)
val internalConfirmedProfile = internalUnconfirmedProfile.copy(confirmed=true)
val unconfirmedProfile = UserProfile(Some(internalUnconfirmedProfile),externalProfile)
val confirmedProfile = UserProfile(Some(internalConfirmedProfile),externalProfile)
val origUser = User(testEnv.mockHelperMethods.getUniqueID(),unconfirmedProfile)
val confirmedUser = origUser.copy(profile = confirmedProfile)
//the argument passed to update is part of test. The function confirmSignupforUser should pass a confirmed profile
when(testEnv.mockUserRepository.update(confirmedUser)).thenReturn(Future{Some(confirmedUser)})
//// await is from play.api.test.FutureAwaits
val updatedUserOption:Option[User] = await[Option[User]](testEnv.controller.confirmSignupforUser(origUser))
println(s"received updated user option ${updatedUserOption}")
updatedUserOption mustBe Some(confirmedUser)
}
}
我不确定我是否正确测试了该方法。我可以检查confirmed 字段是否已更改的唯一方法是查看confirmSignupforUser 的返回值。但我实际上是在模拟该值,并且我已经在模拟值(when(testEnv.mockUserRepository.update(confirmedUser)).thenReturn(Future{Some(confirmedUser)}))中将字段confirmed 设置为true。
我知道代码有效,因为在上面的模拟中,update 方法需要confirmedUser,换句话说,confirmed 字段设置为true 的用户。因此,如果我的代码不工作,update 将被调用 user 其 confirmed 字段为 false 和 mockito 将失败。
这是测试方法的正确方法还是有更好的方法?
【问题讨论】:
标签: scala mockito playframework-2.6