首页 > 解决方案 > 如何模拟引发异常的方法

问题描述

以下方法抛出一个exceptionif a questionis not found

  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
      })
    }
  }

我在 a 中这样称呼它controller

    def function1(){...
        val res = for{existingQuestion <- questionsRepository.getQuestionFromQuestionID(questionKey) 
res.recover{
case exception =>...
}...}
    ...}

我正在编写一个测试来function1模拟抛出异常。我写了以下内容,但是dead code在编译代码时出现错误。

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

错误

Error:(92, 9) dead code following this construct
        throw QuestionNotFoundException()

我将代码更改为

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

但是测试用例失败并出现错误

Checked exception is invalid for this method!
Invalid: utilities.QuestionNotFoundException: Question not found
org.mockito.exceptions.base.MockitoException: 
Checked exception is invalid for this method!
Invalid: utilities.QuestionNotFoundException: Question not found

如何模拟异常场景?

标签: scalaplayframework-2.6

解决方案


对于具有返回值的方法,您可以使用.thenThrow(我假设您使用的是 mockito,因为 scalamock 使用不同的约定)

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

如果方法是void( Unit) 类型,则使用doThrow(ex).when(mock).call

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

推荐阅读