3

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.

2 Answers2

9

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.

Hash
  • 7,726
  • 9
  • 34
  • 53
7

I don't think you should test private constructors, since they are part of the implementation. Write tests only for API methods with well-defined contracts.

siledh
  • 3,268
  • 2
  • 16
  • 29
  • 1
    This is a good point. I would agree that its usually (though not always) true. . I've found a few situations where I wanted to test a private method or constructor, and couldn't get at it via the public API for one reason or another. – Jasper Blues Oct 31 '13 at 06:57
  • 1
    The reason unfortunately is code test coverage scanners, e.g., Sonar, Emma. – JeeBee Dec 17 '15 at 16:48