【问题标题】:Configuration Reflections to scan test classes扫描测试类的配置反射
【发布时间】:2016-08-02 09:14:41
【问题描述】:

使用Reflections 库,我编写了一个简单的实用程序类,它索引所有测试方法及其注释。反射库可以帮助我:

Reflections reflections = new Reflections(new ConfigurationBuilder()
  .setUrls(ClasspathHelper.forPackage(packageToIndex))
  .filterInputsBy(new FilterBuilder().includePackage(packageToIndex))
  .setScanners(
    new SubTypesScanner(false),
    new TypeAnnotationsScanner(),
    new MethodAnnotationsScanner()));

Set testMethods = reflections.getMethodsAnnotatedWith(Test.class);

如果我的实用程序类位于源根目录 (src/main/java),它会按预期找到所有测试方法。

但是,如果它位于测试根目录 (src/test/java),则找不到测试方法。

我应该如何为反射定义 ConfigurationBuilder 以便它适用于后一种情况?

【问题讨论】:

  • 测试根和源根是否相等?
  • @dit,不,我更正了我的问题

标签: java reflections


【解决方案1】:

我找到了解决方案。创建 ConfigurationBuilder 时,定义很重要:

  • 注册额外的类加载器,以了解测试类的位置
  • 注册测试类位置

这是一个示例实现:

URL testClassesURL = Paths.get("target/test-classes").toUri().toURL();

URLClassLoader classLoader = URLClassLoader.newInstance(new URL[]{testClassesURL}, 
   ClasspathHelper.staticClassLoader());

Reflections reflections = new Reflections(new ConfigurationBuilder()
        .addUrls(ClasspathHelper.forPackage(packageToIndex, classLoader))
        .addClassLoader(classLoader)
        .filterInputsBy(new FilterBuilder().includePackage(packageToIndex))
        .setScanners(
                new SubTypesScanner(false),
                new TypeAnnotationsScanner(),
                new MethodAnnotationsScanner()));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 2018-07-22
    • 2013-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多