为了账号安全,请及时绑定邮箱和手机立即绑定

返回类对象数组的方法读取文件

返回类对象数组的方法读取文件

qq_花开花谢_0 2021-07-20 17:01:46
我使用 JUnit 来启动保存@SuiteClasses参数的主测试类。此参数包含类对象数组,即@SuiteClasses({Test0.class, Test1.class, Test2.class})我想将这些类名称(Test0、Test1、[..])保存在外部文件中(我不在乎它是否是 XML、CSV、TXT 等),这些文件将以任何方式保存所述名称 - 是否无关紧要它由逗号、换行符或新的 XML 对象分隔。我的理想方法应该可以这样使用@SuiteClasses(methodReadingFileAndReturningClassObjs)有可能吗?我怎样才能做到这一点?
查看完整描述

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方法就是这样做的。


查看完整回答
反对 回复 2021-07-23
  • 1 回答
  • 0 关注
  • 148 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信