Mockito 如何模拟和断言抛出的异常? [英] Mockito How to mock and assert a thrown exception?

查看:104
本文介绍了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 单独不是处理异常的最佳解决方案,使用 MockitoCatch-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);

示例代码

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆