views:

70

answers:

2

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 for 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();
     }
  }
}
+4  A: 

Right before invoking addMessage(), call Thread.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 a LinkedBlockingQueue, an InterruptedException will be raised, even if no waiting is required for the put (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.

erickson
+1, this is true. Aim for 80-85 and you'll avoid all the problems like this and still keep your code pretty pristine.
BjornS
+3  A: 

Use a mocking library like Easymock and inject a mock LinkedBlockingQueue

i.e.

@Test(expect=InterruptedException.class)
public void testInterruptedException() {
    LinkedBlockingQueue queue = EasyMock.createMock(LinkedBlockingQueue.class);
    ExampleMessage message = new ExampleMessage();
    queue.put(message);
    expectLastCall.andThrow(new InterruptedException()); 
    replay(queue);
    someObject.setQueue(queue);
    someObject.addMessage(msg);
}
Peter Tillemans
Absolutely the best way. Solves many more problems than this as well.
Bill K