Unit test using the Reflections google library fails only when executed by Maven

前端 未结 5 1219
有刺的猬
有刺的猬 2020-12-18 00:00

I am using the Google Reflections library for querying certain resources in the classpath. Those resources are located in the same location than the classes in my project.

5条回答
  •  情深已故
    2020-12-18 00:19

    Solved it. Posting the solution in case someone find the same problem in the future.

    When executing the unit tests of a project, Maven does not (explicitly) include in the classpath all its dependencies. Instead, it declares a dependency on a tmp jar located in "target/surefire/surefirebooter_NUMBER_THAT_LOOKS_LIKE_TIME_STAMP.jar". This jar only contains a manifest file that declares a classpath for the project.

    The method forClassLoader in the Reflections library does not return a set of urls with the effective classpath (i.e., classpath entries in manifest files are ignored). To overcome this, I just implemented this simple method:

    public static Set effectiveClassPathUrls(ClassLoader... classLoaders) {
        return ClasspathHelper.forManifest(ClasspathHelper.forClassLoader(classLoaders));
    }
    

    The method forManifest (also part of the Reflections library) adds to the set of classpath urls sent as parameter, the missing classpath entries declared in manifest files of any jar files contained in the set. In this way the method returns a set of URLs with the effective classpath of the project.

提交回复
热议问题