Search code examples
javajunitjmockitinterrupted-exception

How to throw `InterruptedException` while junit testing my class?


I am trying to write some junit for a class which is using CountDownLatch and I am using jmockit library for junit testing.

public class MappedData {

    private static final AtomicReference<Map<String, Map<Integer, String>>> mapped1 = new AtomicReference<Map<String, Map<Integer, String>>>();
    private static final AtomicReference<Map<String, Map<Integer, String>>> mapped2 = new AtomicReference<Map<String, Map<Integer, String>>>();
    private static final CountDownLatch firstSet = new CountDownLatch(1);

    public static Map<String, Map<Integer, String>> getMapped1Table() {
    try {
        firstSet.await();
    } catch (InterruptedException e) {
        throw new IllegalStateException(e);
    }
    return mapped1.get();
    }

    public static Map<String, Map<Integer, String>> getMapped2Table() {
    try {
        firstSet.await();
    } catch (InterruptedException e) {
        throw new IllegalStateException(e);
    }
    return mapped2.get();
    }
}

What is the easiest way to make sure that in the getMapped1Table and getMapped2Table method - I am able to throw an InterruptedException so that I can cover that scenario as well. If you take a look into those two methods, I have a catch block which I am not able to cover.

MappedData.getMapped1Table()

Is there any way I can make sure that my above two methods are throwing InterruptedException?

Update:-

What I am trying to do is - how to get firstSet.await() to throw an InterruptedException when I am junit testing.


Solution

  • Here is the simplest way to write the test with JMockit:

    public class MappedDataTest
    {
        @Test
        public void getMappedTableHandlesInterruptedException(
            @Mocked final CountDownLatch anyLatch) throws Exception
        {
            final InterruptedException interrupt = new InterruptedException();
            new NonStrictExpectations() {{ anyLatch.await(); result = interrupt; }};
    
            try {
                MappedData.getMapped1Table();
                fail();
            }
            catch (IllegalStateException e) {
                assertSame(interrupt, e.getCause());
            }
        }
    }