How to write unit test for "InterruptedException"
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.
Use a mocking library like Easymock and inject a mock LinkedBlockingQueue
i.e.
@Test(expected=InterruptedException.class)
public void testInterruptedException() {
LinkedBlockingQueue queue = EasyMock.createMock(LinkedBlockingQueue.class);
ExampleMessage message = new ExampleMessage();
queue.put(message);
EasyMock.expectLastCall.andThrow(new InterruptedException());
replay(queue);
someObject.setQueue(queue);
someObject.addMessage(msg);
}
As stated above just make use Thread.currentThread().interrupt()
if you caught InterruptedException
and isn't going to rethrow it.
As for the unit testing. Test this way: Assertions.assertThat(Thread.interrupted()).isTrue();
. It both checks that the thread was interrupted and clears the interruption flag so that it won't break other test, code coverage or anything below.