Junit3答案:创建一个TestSuite,创建您需要的TestCases的实例,并根据您的动态数据初始化每个TestCase。该套件将作为一个整体在单个JVM实例中运行,但各个TestCases彼此独立(setUp,tearDown被调用,错误处理正确,报告给出您要求的内容等)。
实际的实现可能有点笨拙,因为TestCase将测试的名称与要运行的METHOD混合在一起,但这可以解决。
我们通常只将套件与动态测试用例组合到同一个类中,然后使用suite()方法获取TestSuite。例如,Ant的JUnit任务足够聪明,可以注意到这一点。
public class DynamicTest extends TestCase {
String filename ;
public DynamicTest (String crntFile) {
super("testMethod");
filename = crntFile ;
}
// This is gross, but necessary if you want to be able to
// distinguish which test failed - otherwise they all share
// the name DynamicTest.testMethod.
public String getName() {
return this.getClass().getName() + " : " + filename ;
}
// Here's the actual test
public void testMethod() {
File f = new File(filename) ;
assertTrue(f.exists()) ;
}
// Here's the magic
public static TestSuite suite() {
TestSuite s = new TestSuite() ;
for (String crntFile : getListOfFiles()) {
s.addTest(new DynamicTest(crntFile)) ;
}
return s ;
}
}
如果您愿意,您当然可以将TestSuite从TestCase中分离出来。但是,TestCase并没有很好地支持,所以如果你的测试被自动检测到,你需要对你的命名约定有一些关注。
我需要使用BaseTestRunner吗? – benstpierre 2010-04-15 17:06:51