In attempts of 100% code coverage, I came across a situation where I need to unit test block of code that catches an InterruptedException. How does one correctly unit test this? (JUnit 4 syntax please)
private final LinkedBlockingQueue<ExampleMessage> m_Queue;
public void addMessage(ExampleMessage hm) {
if( hm!=null){
try {
m_Queue.put(hm);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Right before invoking
addMessage(), callThread.currentThread().interrupt(). This will set the “interrupt” status flag on the thread.If the interrupted status is set when the call to
put()is made on aLinkedBlockingQueue, anInterruptedExceptionwill be raised, even if no waiting is required for theput(the lock is un-contended).By the way, some efforts to reach 100% coverage are counter-productive and can actually degrade the quality of code.