如果您绝对需要实现100%的代码覆盖率 - 其优点可以在别处讨论:) - 您可以在测试中使用反射来实现它。作为习惯,当我实现一个静态实用类时,我添加了一个私有构造函数来确保无法创建该类的实例。例如:
/**
* Constructs a new MyUtilities.
* @throws InstantiationException
*/
private MyUtilities() throws InstantiationException
{
throw new InstantiationException("Instances of this type are forbidden.");
}
然后测试可能是这个样子:
@Test
public void Test_Constructor_Throws_Exception() throws IllegalAccessException, InstantiationException {
final Class<?> cls = MyUtilties.class;
final Constructor<?> c = cls.getDeclaredConstructors()[0];
c.setAccessible(true);
Throwable targetException = null;
try {
c.newInstance((Object[])null);
} catch (InvocationTargetException ite) {
targetException = ite.getTargetException();
}
assertNotNull(targetException);
assertEquals(targetException.getClass(), InstantiationException.class);
}
基本上,你在做什么在这里越来越名字的类,这个类的类型寻找构造,设置它公开(调用setAccessible
),调用没有参数的构造函数,然后确保抛出的目标异常是InstantiationException
。
无论如何,正如你所说的,这里100%的代码覆盖率要求是一种痛苦,但它听起来好像不在你的手中,所以你对此无能为力。实际上,我在自己的代码中使用了与上面类似的方法,并且我确实发现它有益处,但不是从测试角度来看。相反,它只是帮助我学习更多关于思考的知识,而不是我之前所知道的:)
第三种方法在我看来是最好的,因为它根本不影响代码(只有测试)。我会采取这种方式。谢谢你的帮助。 – 2012-03-14 11:43:16