Mockito 如何模拟和断言抛出的异常? [英] Mockito How to mock and assert a thrown exception?
本文介绍了Mockito 如何模拟和断言抛出的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 junit 测试中使用 mockito.您如何使异常发生然后断言它具有(通用伪代码)
I'm using mockito in a junit test. How do you make an exception happen and then assert that it has (generic pseudo-code)
推荐答案
BDD Style解决方案(更新到 Java 8)
Mockito 单独不是处理异常的最佳解决方案,使用 Mockito 和 Catch-Exception
BDD Style Solution (Updated to Java 8)
Mockito alone is not the best solution for handling exceptions, use Mockito with Catch-Exception
given(otherServiceMock.bar()).willThrow(new MyException());
when(() -> myService.foo());
then(caughtException()).isInstanceOf(MyException.class);
示例代码
- Mockito + Catch-Exception + Assertj 完整示例
这篇关于Mockito 如何模拟和断言抛出的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文