Search code examples
javajunitjunit4emma

Coverage for private constructor junit/emma


how can i write a @test class for a private constructor. i want to cover it with emma tool too.

public final class Product {

    private Product() {

    }
}

can someone suggest a simple way?

thanks.


Solution

  • The best way to test private methods is to use Reflection.

    There are many ways, but I would simple do this;

    @Test
        public void testConstructorIsPrivate() throws Exception {
          Constructor constructor = Product.class.getDeclaredConstructor();
          assertTrue(Modifier.isPrivate(constructor.getModifiers()));
          constructor.setAccessible(true);
          constructor.newInstance();
        }
    

    This will cover the constructor when running the coverage tool emma.