译自:http://junit.sourceforge.net/doc/cookstour/cookstour.htm
不是直接翻译。
1. Command 模式
一个TestCase就是一个Command,command内容都写在run方法里。
2. A best practice is from Smalltalk, "Collecting Parameter":
当你需要收集多个方法的运行结果,比较好的一个方式就是每个方法增加一个参数,用这个参数object来收集结果
3.
protected void run(final TestCase test) {
startTest(test);
Protectable p= new Protectable() {
public void protect() throws Throwable {
test.runBare();
}
};
runProtected(test, p);
endTest(test);
}
提供可继承实现run方法,其中的protect()方法的具体实现也可以另外写,这里保留了runProtected()方法不用被继承。
4. No stupid subclasses
while (Test.class.isAssignableFrom(superClass)) {
Method[] methods= superClass.getDeclaredMethods(); //得到所有public的方法
for (int i= 0; i < methods.length; i++) {
addTestMethod(methods[i], names, theClass); //判断是否以test开头,返回类型是void,无参数,如果是,则加入names中
}
superClass= superClass.getSuperclass();
}
if (fTests.size() == 0)
addTest(warning("No tests found in "+theClass.getName()));
private void addTestMethod(Method m, Vector names, Class theClass) {
String name= m.getName();
if (names.contains(name))
return;
if (! isPublicTestMethod(m)) {
if (isTestMethod(m))
addTest(warning("Test method isn't public: "+m.getName()));
return;
}
names.addElement(name);
addTest(createTest(theClass, name));
}
static public Test createTest(Class theClass, String name) {
Constructor constructor;
try {
constructor= getTestConstructor(theClass);
} catch (NoSuchMethodException e) {
return warning("Class "+theClass.getName()+" has no public constructor TestCase(String name) or TestCase()");
}
Object test;
try {
if (constructor.getParameterTypes().length == 0) {
test= constructor.newInstance(new Object[0]); //***********这里是关键,根据各个方法的名字创建了若干个TestCase对象,以方法的名字命名。
if (test instanceof TestCase)
((TestCase) test).setName(name);
} else {
test= constructor.newInstance(new Object[]{name});
}
} catch (InstantiationException e) {
return(warning("Cannot instantiate test case: "+name+" ("+exceptionToString(e)+")"));
} catch (InvocationTargetException e) {
return(warning("Exception in constructor: "+name+" ("+exceptionToString(e.getTargetException())+")"));
} catch (IllegalAccessException e) {
return(warning("Cannot access test case: "+name+" ("+exceptionToString(e)+")"));
}
return (Test) test;
}
5. 不用去考虑一个或多个 -- TestSuite
TestSuite和TestCase都实现了Test接口,TestSuite中放了一个Vector,可以放TestSuite/TestCase这些实现了Test接口的对象。
6. 总结
7.其他
theClass.getConstructor(args); 得到一个类的构造函数,其仅含有一个String的参数
theClass.getConstructor(new Class[0]); 得到一个类的无参数构造函数
上面两个返回的是Constructor
Modifier.isPublic(theClass.getModifiers()) 可以判断一个类是否是public的
Modifier.isPublic(m.getModifiers() 可以判断一个方法是否是public的
Test.class.isAssignableFrom(superClass)
Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter.