I am using Maven with Eclipse (using M2E) to create 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 the test using the built-in Eclipse JUnit4 Runner, it cannot pick up the services and the tests fail.
Is there something I need to do to manually add META-INF / services to the JUnit build path? I could not get it to work either in src / main / resources / META-INF / services, or in src / main / java / META-INF / services. Is this related to how M2E sets the build path? I made a test in a completely new project, and it still failed.
Base code that doesn't work:
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 is as follows:
@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 used the MetaInfServices generator http://weblogs.java.net/blog/kohsuke/archive/2009/03/my_project_of_t.html , but when I deleted it and manually created the files manually, it still failed in the same way for Eclipse when it is executed at startup using the Maven Surefire plugin.
source share