How to unit test to give coverage of exception branches

淺唱寂寞╮ 提交于 2019-12-13 17:46:25

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/17751139/how-to-unit-test-to-give-coverage-of-exception-branches

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!