How to unit test to give coverage of exception bra

2019-07-24 16:59发布

问题:

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