恢复方法未处理异常

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

此方法抛出exception

  @throws(classOf[QuestionNotFoundException])
  def getQuestionFromQuestionID(questionKey: PracticeQuestionKeys) = {
    logger.trace(s"getting question with keys ${questionKey}")
    val practiceQuestionFuture: Future[Option[PracticeQuestion]] = findOne(questionKey)
    for (questionOption <- practiceQuestionFuture) yield {
      questionOption.fold(throw QuestionNotFoundException())(question => {
        logger.trace("got question " + question)
        question
      })
    }
  }

我如下使用它

def function1 = {
...
val res = for{existingQuestion <- questionsRepository.getQuestionFromQuestionID(questionKey){..}
res.recover {
                     case exception => {
                       logger.trace(s"exception ${exception}")
                       Ok(Json.toJson(JsonResultError(messagesApi("error.answerAdditionFail")(langs.availables(0))+". "+exception.getMessage())))
                     }
...
}

我想测试function1是否处理了抛出的异常。我已经编写了以下测试用例

"function" should {
    "should return error if the question id is not correct" in {
      ...

      when(answerTestEnv.mockPracticeQuestionsRepository.getQuestionFromQuestionID(ArgumentMatchers.any[PracticeQuestionKeys])).thenThrow(
        QuestionNotFoundException()
      )




      val response:Accumulator[ByteString,Result] = controller.function1(request)
      //note that run is how accumulator gets the data and starts processing it. no parameter means no data
      val resultOfAccumulatorRun:Future[Result] = response.run(ByteString(body))
      val responseBody = contentAsJson(resultOfAccumulatorRun)(Timeout(Duration(5000,"millis")),TestEnvImplicits.mat)

      println(s"received response ${responseBody}")
      val result = (responseBody \ "result").get.as[String]

      val additionalInfo = (responseBody \ "additional-info").get.as[String]

      result mustBe "error"
      additionalInfo mustBe components.messagesApi("error.answerAdditionFail")(components.langs.availables(0))+". "+QuestionNotFoundException().msg


    }

}

但是当我运行测试用例时,会抛出Exception,但似乎res.recover无法处理它。我在控制台中看到了。

Question not found
utilities.QuestionNotFoundException: Question not found
    at controllers.AnswerController.$anonfun$newAnswer$1(AnswerController.scala:428)

为什么t res.recover`无法处理。

scala playframework-2.6
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.