如何单元测试给予例外分支覆盖(How to unit test to give coverage o

2019-10-18 09:21发布

我编写单元测试与JUnit4和针对的Mockito我的申请,我想充分覆盖。 但我不完全理解盖异常是如何分支。 例如:

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

我怎样才能从测试异常调用?

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


文章来源: How to unit test to give coverage of exception branches