1

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

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

我如何从测试异常中调用?

4

1 回答 1

2

虽然您可能无法轻松地将异常插入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);
  // ...
}
于 2013-07-19T21:36:21.400 回答