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

查看:4286
本文介绍了Mockito如何模拟和断言抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个junit测试中使用mockito。你如何发生异常,然后断言它有(通用伪代码)

解决方案

BDD 样式解决方案



Mockito 独自一人不是处理异常的最佳解决方案,使用 Mockito Catch-Exception



Mockito + Catch-Exception + AssertJ



 给定(otherServiceMock.bar())。willThrow(new MyException ()); 

当(myService).foo();

then(caughtException())。isInstanceOf(MyException.class);



示例代码





依赖关系




  • eu.codearte.catch-exception:catch-exception:1.3 .3

  • org.assertj:assertj-core:1.7.0



Disadvantage




  • 仅支持1.10.8的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 Solution

Mockito alone is not the best solution for handling exceptions, use Mockito with Catch-Exception

Mockito + Catch-Exception + AssertJ

given(otherServiceMock.bar()).willThrow(new MyException());

when(myService).foo();

then(caughtException()).isInstanceOf(MyException.class);

Sample code

Dependencies

  • eu.codearte.catch-exception:catch-exception:1.3.3
  • org.assertj:assertj-core:1.7.0

Disadvantage

  • Only Mockito up to 1.10.8 is supported

这篇关于Mockito如何模拟和断言抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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