1 回答
TA贡献1842条经验 获得超21个赞
我意识到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方法就是这样做的。
添加回答
举报