如何将测试覆盖率添加到私有构造函数? [英] How to add test coverage to a private constructor?
问题描述
这是代码:
package com.XXX;
public final class Foo {
private Foo() {
// intentionally empty
}
public static int bar() {
return 1;
}
}
这是测试:
package com.XXX;
public FooTest {
@Test
void testValidatesThatBarWorks() {
int result = Foo.bar();
assertEquals(1, result);
}
@Test(expected = java.lang.IllegalAccessException.class)
void testValidatesThatClassFooIsNotInstantiable() {
Class cls = Class.forName("com.XXX.Foo");
cls.newInstance(); // exception here
}
}
工作正常,课程经过测试。但Cobertura表示,该类私有构造函数的代码覆盖率为零。我们如何为这样的私有构造函数添加测试覆盖率?
Works fine, the class is tested. But Cobertura says that there is zero code coverage of the private constructor of the class. How can we add test coverage to such a private constructor?
推荐答案
嗯,有些方法可以使用反射等 - 但是是不是真的值得吗?这是一个永远不会被称为的构造函数,对吗?
Well, there are ways you could potentially use reflection etc - but is it really worth it? This is a constructor which should never be called, right?
如果有一个注释或类似的东西,你可以添加到类来制作Cobertura明白它不会被调用,这样做:我认为值得通过箍来人为地增加覆盖率。
If there's an annotation or anything similar that you can add to the class to make Cobertura understand that it won't be called, do that: I don't think it's worth going through hoops to add coverage artificially.
编辑:如果没办法这样做,只是略微减少了覆盖范围。请记住,覆盖范围应该是对你有用的东西 - 你应该负责该工具,而不是相反。
If there's no way of doing it, just live with the slightly reduced coverage. Remember that coverage is meant to be something which is useful to you - you should be in charge of the tool, not the other way round.
这篇关于如何将测试覆盖率添加到私有构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!