【问题标题】:how to test that the function under test has thrown an exception如何测试被测函数是否抛出异常
【发布时间】:2019-11-26 13:42:59
【问题描述】:

在我的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???

    }
  }

【问题讨论】:

标签: scalatest playframework-2.6


【解决方案1】:

感谢 JB 尼泽特。我必须承认我很懒惰!正确的方法是使用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))

【讨论】:

    猜你喜欢
    • 2016-06-16
    • 2021-02-26
    • 1970-01-01
    • 2015-06-04
    • 2012-11-19
    • 2015-04-04
    • 2021-06-20
    • 2018-01-16
    • 2012-06-09
    相关资源
    最近更新 更多