how to mock a method that throws an exception

576 views Asked by At

The following method throws an exception if a question is 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
      })
    }
  }

I call it like the following in a controller.

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

I am writing a test for function1 simulating that an exception is thrown. I wrote the following but I get dead code error when I compile the code.

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

Error

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

I changed the code to

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

But the test case fails with error

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

How can I simulate the exception scenario?

1

There are 1 answers

2
Mateusz Kubuszok On

For methods with return value you can use .thenThrow (I's assuming you are using mockito, because scalamock uses different conventions)

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

and if the method is of type void (Unit) you use doThrow(ex).when(mock).call:

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