I am using Maven with Eclipse (using M2E) to build a project that relies on java.util.ServiceLoader to dynamically load some factory classes. It works fine when I run it in Maven, but when I run a test using the inbuilt Eclipse JUnit4 Runner, it fails to pick up the services and the tests do not succeed.
Is there something I need to do to manually add the META-INF/services to the JUnit build path? I couldn't make it work in either src/main/resources/META-INF/services or src/main/java/META-INF/services. Is it related to the way M2E sets up the build path? I made up the test in a completely new project and it still failed.
The basic code that is failing is:
public class TestServiceLoader<S>
{
public TestServiceLoader(final Class<S> serviceClass)
{
ServiceLoader<S> serviceLoader =
java.util.ServiceLoader.load(serviceClass, serviceClass.getClassLoader());
Iterator<S> services = serviceLoader.iterator();
if(!services.hasNext())
{
throw new RuntimeException("Failed to get any services for this class");
}
}
}
The test looks like:
@Test
public final void testTestServiceLoader()
{
TestServiceLoader<TestFactory> serviceLoader = new TestServiceLoader<TestFactory>(TestFactory.class);
}
TestFactory is defined as:
public interface TestFactory
{
}
TestFactoryImpl is defined as:
public class TestFactoryImpl implements TestFactory
{
}
I originally was using the MetaInfServices generator from http://weblogs.java.net/blog/kohsuke/archive/2009/03/my_project_of_t.html but when I removed that and manually created the files by hand, it was still failing in the same way for Eclipse while succeeding when run using the Maven Surefire plugin.
The M2E developers appear to believe that any resources will affect a maven build, even in the case where META-INF/services/ is a functional part, albeit a resource:
"Actually project resource folder doesn’t really need to be added to the buildpath (Maven Builder is going to work without it), but it been considered convenient and look better in the Package Explorer and other Eclipse views." M2E FAQ
If you want to hack around it, you can apparently encode a special M2E profile into your pom.xml files to make the M2E incremental build filter and copy resources Sonatype M2Eclipse Wiki
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With