FactorCalculator类提供的接口很简单:
factor: 分解一个数获取素因子的方法。
isPrime: 判断一个数是否素数的方法。
isDivisor: 判断一个数是否能被另一个数整除的方法。
这些public方法可以构成一个数学库的API。
要测试FactorCalculator,你可以创建一个有main方法可以从命令行调用的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。有时候抛出异常才是某段代码的正确行为,测试这样的代码时,你必须捕获这个异常,看它是否你想要的。如果抛出的不是你想要的异常,你应该把它扔给(异常)处理链的下一级。如果这段代码应该有异常,但测试时没有抛出,你要抛出你自己定义的异常,来通知程序功能错误。你应该使用与下文中要介绍的JUnit测试代码类似的模式,来测试那种本来应该抛出一个或多个异常的部分代码。