我正在使用 jmockit 来模拟我的类以进行单元测试。到目前为止一切都运行良好。
我有一个线程安全且单例的工厂,如下所示:
因此,对于下面的类,我可以获得 50% 的行覆盖率,因为我无法覆盖私有(private)构造函数 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;
}
}
我的问题是 - 有什么方法可以覆盖 TestFactory()
私有(private)构造函数,以便我可以在此类的 Cobertura 报告中获得 100% 的行覆盖率?
最佳答案
使用反射或仅 mockit.Deencapsulation.newInstance()
调用它。写一个这样的测试方法
@Test
public void privateConstructorCoverage() throws Exception {
Deencapsulation.newInstance(TestFactory.class);
}
Provides utility methods that enable access to (ie "de-encapsulate") otherwise non-accessible fields, methods and constructors belonging to code under test.
关于java - 如何在行覆盖中包含私有(private)构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30366154/