如何测试被测函数已引发异常

时间:2019-07-17 16:40:22

标签: scalatest playframework-2.6

在我的scalaplay代码中,一个函数抛出异常

case None => {
            println("error in updating password info")

            throw new Exception("error in updating password info") //TODOM - refine errors. Make errors well defined. Pick from config/env file
          }

我想测试上面的代码,但是我不知道如何测试是否抛出了Exception。我写的规范是

  "PasswordRepository Specs" should {
    "should not add password for non-existing user" in {

      val newPassword = PasswordInfo("newHasher","newPassword",Some("newSalt"))
      when(repoTestEnv.mockUserRepository.findOne(ArgumentMatchers.any())).thenReturn(Future{None}) //THIS WILL CAUSE EXCEPTION CODE TO GET EXECUTED

      val passwordRepository = new PasswordRepository(repoTestEnv.testEnv.mockHelperMethods,repoTestEnv.mockUserRepository)

      println(s"adding password ${newPassword}")
      val passwordInfo:PasswordInfo = await[PasswordInfo](passwordRepository.add(repoTestEnv.testEnv.loginInfo,newPassword))(Timeout(Duration(5000,"millis"))) //add SHOULD THROW AN EXCEPTION BUT HOW DO I TEST IT???

    }
  }

1 个答案:

答案 0 :(得分:0)

感谢JB Nizet。我必须承认我很懒!正确的方法是使用assertThrowinterrupt。例如

val exception:scalatest.Assertion = assertThrows[java.lang.Exception]( await[PasswordInfo](passwordRepository.add(repoTestEnv.testEnv.loginInfo,newPassword))(Timeout(Duration(5000,"millis"))))

  val exception = intercept[java.lang.Exception]( await[Unit](passwordRepository.remove(repoTestEnv.testEnv.loginInfo))(Timeout(Duration(5000,"millis"))))
  println(s"exception is ${exception}")
  exception.getMessage() mustBe repoTestEnv.testEnv.messagesApi("error.passwordDeleteError")(repoTestEnv.testEnv.langs.availables(0))