2016-08-02 2 views
2

Reflectionsライブラリを使用して、すべてのテストメソッドとその注釈をインデックスする簡単なユーティリティクラスを作成しました。ものがたりライブラリは、そのように私を助け:私のユーティリティクラスはソースルート(src/main/java)に位置している場合、期待どおり構成テストクラスをスキャンするためのリフレクション

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/test/java)に配置されている場合、テスト方法は見つけられません。

後者のケースで動作するように、ReflectionsのためにConfigurationBuilderを定義する方法を教えてください。

+0

テストルートとソースルートは等しいですか? – dit

+0

@dit、いいえ、私の質問を修正しました – dzieciou

答えて

2

解決策が見つかりました。 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())); 
関連する問題