我需要帮助理解我测试函数的方式是否正确

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

我编写了这个函数,当用户点击链接时调用该函数。该函数基本上创建了一个用户数据的副本,其中一个字段被更改(从而保持原始值不变,即不可变)然后使用新值更新数据库

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的返回值。但我实际上在嘲笑这个值,我已经将字段confirmed设置为true的模拟值(when(testEnv.mockUserRepository.update(confirmedUser)).thenReturn(Future{Some(confirmedUser)})

我知道代码是有效的,因为在上面的模拟中,update方法需要confirmedUser或换句话说,confirmed字段设置为true的用户。因此,如果我的代码不起作用,update将被调用user,其confirmed字段是falsemockito将失败。

这是测试方法的正确方法还是有更好的方法?

scala mockito playframework-2.6
1个回答
0
投票

您不需要在测试中初始化qazxsw poi。重点是从qazxsw poi开始,运行internalConfirmedProfile方法,并确保输出为confirmed=false

你应该检查两件事:

  1. 检查返回值是否有confirmSignupforUser(你这样做)
  2. 检查存储库是否已使用confirmed=true保存该用户(您不检查)。要检查是否需要在最后从存储库中加载用户。
© www.soinside.com 2019 - 2024. All rights reserved.