scala - 如何模拟引发异常的方法
问题描述
以下方法抛出一个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
})
}
}
我在 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
如何模拟异常场景?
解决方案
对于具有返回值的方法,您可以使用.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])
推荐阅读
- android-studio - 上传到 Play 商店时出现无效的 APK 文件错误
- php - CURL 登录到使用令牌的页面
- android - 如何从 android studio 3.2 中删除 generatedJava
- algorithm - 计算机算法的可扩展性
- powerbi - Power BI - 通过表 A 的第 1 列中的条目重命名表 B
- button - 在哪里可以找到要在 vuetify 中使用的图标列表?
- c++ - 通过 const 引用获取字符串
- amazon-web-services - AWS ec2 实例线程饥饿或时钟跳跃
- ios - 如何在 swift 4.0 中获取 firebase-realtime-database 中的特定值
- angularjs - Angular 5 和遗留的 AngularJs 应用程序可以共存吗?