为什么测试用例抛出异常而不是发送JSON响应

问题描述

我正在测试我的代码的这一部分,当接收到异常时,它应该返回一个json响应。

val res = for(result<-service.handleTransaction(profile)) yield {
                Ok(Json.toJson(JsonResultSuccess((messagesApi("success.userSignupConfirmationEmailSent"))(langs.availables(0)))))
              }
              res.recover {
                case exception: UnconfirmedUserException => {
                  logger.trace(s"unconfirmed user")
                  Ok(Json.toJson(JsonResultSuccess((messagesApi("success.userSignupConfirmationEmailSent"))(langs.availables(0)))))
                }
                case exception => {
                  logger.trace(s"got error in handling transaction ${exception}")
                  Ok(Json.toJson(JsonResultError(exception.getMessage)))
                }

我正在测试以下代码

"test that signup request from an existing un-confirmed user should be successful" in {
  val jsonBody = Json.parse(
    """
      {
         "external-profile":{
            "email":"test@test.com","firstname":"fn","lastname":"ln","password":"aA1!1111"
         }
      }
    """)

  val userTestEnv = new UserControllerSpecTestEnv(components=components)
  

  val exceptionInProcessing = new UnconfirmedUserException(userTestEnv.testEnv.user)
  when(userTestEnv.mockService.handleTransaction(ArgumentMatchers.any[UserProfile]))
    .thenReturn(
      Future.failed(exceptionInProcessing)
    )


  val request: Request[AnyContentAsJson] = FakeRequest("POST","ws/users/signup",Headers(("someH" -> "someV")),new AnyContentAsJson(jsonBody))
  logger.trace(s"sending sign up request ${request}")

  val response = userTestEnv.controller.signupUser(request)
  val responseBodyAsJsValue = contentAsJson(response)
  logger.trace(s"received response of sign up ${responseBodyAsJsValue}")
  val result = (responseBodyAsJsValue \ "result").get.as[String]
  val message = (responseBodyAsJsValue \ "additional-info").get.as[String]
  //responseBodyAsJsValue.\("result").
  result mustBe "success"
  message mustBe components.messagesApi("success.userSignupConfirmationEmailSent")(components.langs.availables(0))


}

上面的测试失败了,因为异常没有停止在userTestEnv.controller.signupUser(request)

我必须使用intercept来处理测试用例

"test that error is returned if processing on sign up request fails" in {

...

val receivedException = intercept[UnconfirmedUserException](await[Result](userTestEnv.controller.signupUser(request))(Timeout(Duration(5000,"millis"))))
      logger.trace(s"exception is ${receivedException}")
      receivedException.getMessage() mustBe exceptionInProcessing.getMessage
...
    }

为什么我必须使用interceptuserTestEnv.controller.signupUser(request)是否应该处理异常并返回响应?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...