如何模拟一个抛出异常的方法?

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

下面的方法会抛出一个 exception 若是 question 未发现

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

我把它叫做像下面的一个 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

如何模拟异常场景?

scala playframework-2.6
1个回答
0
投票

对于有返回值的方法,你可以使用 .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])
© www.soinside.com 2019 - 2024. All rights reserved.