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.