FactorCalculator類提供的接口很簡單:
factor: 分解一個數(shù)獲取素因子的方法。
isPrime: 判斷一個數(shù)是否素數(shù)的方法。
isDivisor: 判斷一個數(shù)是否能被另一個數(shù)整除的方法。
這些public方法可以構(gòu)成一個數(shù)學(xué)庫的API。
要測試FactorCalculator,你可以創(chuàng)建一個有main方法可以從命令行調(diào)用的Java類。程序列表2是這樣一個測試類。
程序列表2 (CalculatorTest.java, taken from CalculatorTest.java.v1):
public class CalculatorTest {
public static void main(String [] argv) {
FactorCalculator calc = new FactorCalculator();
int[] intArray;
intArray = calc.factor(100);
if (!((intArray.length == 4) && (intArray[0] == 2) && (intArray[1] == 2) && (intArray[2] == 5) && (intArray[3] == 5))) {
throw new RuntimeException("bad factorization of 100");
}
intArray = calc.factor(4);
if (!((intArray.length == 2) && (intArray[0] == 2) && (intArray[1] == 2))) {
throw new RuntimeException("bad factorization of 4");
}
intArray = calc.factor(3);
if (!((intArray.length == 1) && (intArray[0] == 3))) {
throw new RuntimeException("bad factorization of 3");
}
intArray = calc.factor(2);
if (!((intArray.length == 1) && (intArray[0] == 2))) {
throw new RuntimeException("bad factorization of 2");
}
boolean isPrime;
isPrime = calc.isPrime(2);
if (!isPrime) {
throw new RuntimeException("bad isPrime value for 2");
}
isPrime = calc.isPrime(3);
if (!isPrime) {
throw new RuntimeException("bad isPrime value for 3");
}
isPrime = calc.isPrime(4);
if (isPrime) {
throw new RuntimeException("bad isPrime value for 4");
}
try {
isPrime = calc.isPrime(1);
throw new RuntimeException("isPrime should throw exception for numbers less than 2");
} catch (IllegalArgumentException e) {
// do nothing because throwing IAE is the proper action
}
boolean isDivisor;
isDivisor = calc.isDivisor(6, 3);
if (!isDivisor) {
throw new RuntimeException("bad isDivisor value for (6, 3)");
}
isDivisor = calc.isDivisor(5, 2);
if (isDivisor) {
throw new RuntimeException("bad isDivisor value for (5, 2)");
}
try {
isDivisor = calc.isDivisor(6, 0);
throw new RuntimeException("isDivisor should throw exception when potentialDivisor (the second argument) is 0");
} catch (ArithmeticException e) {
// do nothing because throwing AE is the proper action
}
System.out.println("All tests passed.");
}
}
注意這兩個try-catch塊,一個測試isPrime,另一個測試isDivisor。有時候拋出異常才是某段代碼的正確行為,測試這樣的代碼時,你必須捕獲這個異常,看它是否你想要的。如果拋出的不是你想要的異常,你應(yīng)該把它扔給(異常)處理鏈的下一級。如果這段代碼應(yīng)該有異常,但測試時沒有拋出,你要拋出你自己定義的異常,來通知程序功能錯誤。你應(yīng)該使用與下文中要介紹的JUnit測試代碼類似的模式,來測試那種本來應(yīng)該拋出一個或多個異常的部分代碼。