【问题标题】:How to unit test to give coverage of exception branches如何进行单元测试以覆盖异常分支
【发布时间】:2013-07-19 16:32:06
【问题描述】:

我使用 JUnit4 和 Mockito 为我的应用程序编写单元测试,我想全面覆盖。但我不完全理解如何覆盖异常分支。 例如:

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

如何从测试异常中调用?

【问题讨论】:

  • 这只是例外示例。我的意思是调用任何异常
  • 这取决于可能抛出异常的代码以及您感兴趣的异常类型。

标签: unit-testing exception-handling junit4 mockito robolectric


【解决方案1】:

虽然您可能无法轻松地将异常插入到 Thread.sleep 中,尤其是因为它是静态调用的,而不是针对注入的实例,但您可以轻松地存根注入的依赖项,以便在调用时抛出异常:

@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);
  // ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 2021-05-10
    • 2022-12-07
    • 2013-07-08
    • 2011-03-14
    • 2013-10-23
    • 1970-01-01
    相关资源
    最近更新 更多