Search code examples
javaunit-testingmockingcoberturajmockit

How to include private contructor in Line Coverage?


I am using jmockit to mock my classes for unit test purpose. Everything is working fine so far.

I have a factory which is thread safe and singleton as shown below:

So for below class, I am able to get 50% Line Coverage because I am not able to cover private constructor TestFactory().

public class TestFactory {

    // not able to cover this
    private TestFactory() {}

    private static class TestHolder {
        private static final TestClient INSTANCE = new TestClient();
    }

    public static IClient getInstance() {
        return TestHolder.INSTANCE;
    }
}

My question is - Is there any way I can cover TestFactory() private constructor so that I can get 100% Line Coverage in my Cobertura Report for this class?


Solution

  • Invoke it using reflection or just mockit.Deencapsulation.newInstance(). Write a test method like this

    @Test
    public void privateConstructorCoverage() throws Exception {
       Deencapsulation.newInstance(TestFactory.class);
    }
    

    Deencapsulation javadoc

    Provides utility methods that enable access to (ie "de-encapsulate") otherwise non-accessible fields, methods and constructors belonging to code under test.