我使用JUnit启动包含@SuiteClasses
参数的主测试类。此参数保存类对象的数组,即
@SuiteClasses({Test0.class, Test1.class, Test2.class})
我想将这些类名称(Test0,Test1,[..])保存在将以任何方式保存所述名称的外部文件(我不在乎XML,CSV,TXT等)中。不管用逗号,换行符还是新的XML对象分隔它。我理想的方法应该可以像这样使用
@SuiteClasses(methodReadingFileAndReturningClassObjs)
可以吗?我该怎么办?
答案 0 :(得分:0)
我意识到我想到的TestSuite
类是JUnit 3构件,而JUnit 4不再存在。
您可以做的是扩展Suite
运行器来满足您的需要(双关语)。
public class FilelistSuite extends Suite {
public FilelistSuite(Class<?> klass, RunnerBuilder builder) throws InitializationError {
super(klass, loadFromFile(klass));
}
private static Class<?>[] loadFromFile(Class<?> klass) throws InitializationError {
// get annotation
SuiteclassesFile annotation = klass.getAnnotation(SuiteclassesFile.class);
if (annotation == null) {
throw new InitializationError(String.format("class '%s' must have a SuiteclassesFile annotation", klass.getName()));
}
try {
return fromFile(annotation.filename());
} catch (RuntimeException e) {
throw new InitializationError(e.getCause());
}
}
// read file to extract test class names
private static final Class<?>[] fromFile(String filename) throws RuntimeException {
try (Stream<String> lines = Files.lines(Paths.get(filename))) {
return lines
.map(FilelistSuite::forName)
.toArray(Class[]::new);
} catch (IOException ioe) {
throw new RuntimeException(ioe);
} catch (RuntimeException e) {
throw new RuntimeException(e.getCause());
}
}
// wrap Class.forName to be able to use it in the Stream
private static final Class<?> forName(String line) throws RuntimeException {
try {
return Class.forName(line);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
// new annotation for your test suite
public @interface SuiteclassesFile {
public String filename();
}
}
现在,您应该可以使用
注释课程了@RunWith(FilelistSuite.class)
@SuiteclassesFile(filename="/path/to/your/file")
class YourTestClass {}
我实际上并没有尝试过,但是只需要稍作调整即可。
实际上,由于问题的标题只是“返回类对象数组的方法读取文件”,因此fromFile
方法可以做到这一点。