How to unit test to give coverage of exception branches -


i write unit tests junit4 , mockito application , want make full coverage. don't understand how cover exception branches. example:

try {     thread.sleep(100); } catch (interruptedexception e) {     e.printstacktrace(); } 

how can invoke tests exceptions?

while may not able insert exception thread.sleep in particular, because it's being called statically instead of against injected instance, can stub injected dependencies throw exceptions when called:

@test public void shouldhandleexception() throws exception {   // use "thenthrow" standard "when" syntax.   when(dependency.somemethod()).thenthrow(new illegalargumentexception());    // void methods can't use "when" , need yoda syntax instead.   dothrow(new illegalargumentexception()).when(dependency).somevoidmethod();    systemundertest system = new systemundertest(dependency);   // ... } 

Comments