如何进行单元测试以覆盖异常分支 [英] How to unit test to give coverage of exception branches

查看:2271
本文介绍了如何进行单元测试以覆盖异常分支的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用JUnit4和Mockito为我的应用程序编写单元测试,我想全面介绍一下.但是我不完全了解如何覆盖异常分支. 例如:

I write unit tests with JUnit4 and Mockito for my application and I want make full coverage. But I don't fully understand how cover exception branches. For example:

try {
    Thread.sleep(100);
} catch (InterruptedException e) {
    e.printStackTrace();
}

如何从测试异常中调用?

How I can invoke from tests exceptions?

推荐答案

特别是您可能不容易将异常插入Thread.sleep中,因为它是静态调用的,而不是针对注入的实例,因此您可以轻松地存根注入依赖项以在调用时引发异常:

While you may not easily be able to insert an exception into Thread.sleep in particular, because it's being called statically instead of against an injected instance, you can easily stub injected dependencies to throw exceptions when called:

@Test
public void shouldHandleException() throws Exception {
  // Use "thenThrow" for the standard "when" syntax.
  when(dependency.someMethod()).thenThrow(new IllegalArgumentException());

  // Void methods can't use "when" and need the Yoda syntax instead.
  doThrow(new IllegalArgumentException()).when(dependency).someVoidMethod();

  SystemUnderTest system = new SystemUnderTest(dependency);
  // ...
}

这篇关于如何进行单元测试以覆盖异常分支的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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