FactorCalculator類提供的接口很簡(jiǎn)單:
factor: 分解一個(gè)數(shù)獲取素因子的方法。
isPrime: 判斷一個(gè)數(shù)是否素?cái)?shù)的方法。
isDivisor: 判斷一個(gè)數(shù)是否能被另一個(gè)數(shù)整除的方法。
這些public方法可以構(gòu)成一個(gè)數(shù)學(xué)庫(kù)的API。
要測(cè)試FactorCalculator,你可以創(chuàng)建一個(gè)有main方法可以從命令行調(diào)用的Java類。程序列表2是這樣一個(gè)測(cè)試類。
程序列表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.");
}
}
注意這兩個(gè)try-catch塊,一個(gè)測(cè)試isPrime,另一個(gè)測(cè)試isDivisor。有時(shí)候拋出異常才是某段代碼的正確行為,測(cè)試這樣的代碼時(shí),你必須捕獲這個(gè)異常,看它是否你想要的。如果拋出的不是你想要的異常,你應(yīng)該把它扔給(異常)處理鏈的下一級(jí)。如果這段代碼應(yīng)該有異常,但測(cè)試時(shí)沒有拋出,你要拋出你自己定義的異常,來通知程序功能錯(cuò)誤。你應(yīng)該使用與下文中要介紹的JUnit測(cè)試代碼類似的模式,來測(cè)試那種本來應(yīng)該拋出一個(gè)或多個(gè)異常的部分代碼。