如果您絕對需要實現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