私有构造函数junit/emma的覆盖范围

3 java junit emma junit4

如何为私有构造函数编写@test类.我想用emma工具覆盖它.

public final class Product {

    private Product() {

    }
}
Run Code Online (Sandbox Code Playgroud)

有人可以建议一个简单的方法?

谢谢.

Has*_*ash 8

测试私有方法的最佳方法是使用Reflection.

有很多方法,但我会这么做;

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

这将覆盖运行coverage工具emma时的构造函数.


sil*_*edh 7

我不认为你应该测试私有构造函数,因为它们是实现的一部分.仅针对具有明确定义的合同的API方法编写测试.