4

Reflectionsライブラリを使用して、すべてのテスト メソッドとその注釈をインデックス化する単純なユーティリティ クラスを作成しました。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) にある場合は、テスト メソッドが見つかりません。

後者の場合に機能するように、Reflections の ConfigurationBuilder をどのように定義すればよいですか?

4

1 に答える 1

4

解決策を見つけました。作成時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()));
于 2016-08-02T14:30:50.930 に答える