繁体   English   中英

Java 9:ServiceLoader 不会从测试源(模块)加载测试实现

[英]Java 9: ServiceLoader doesn't load Test implementation from Test sources (Module)

我正在使用 Java9 模块系统(在 openjdk11 上运行)

我有

  • 从 Java8 迁移而来,代码包含使用 ServiceLoader 机制的类。
  • 此类的单元测试,它尝试加载两个测试服务实现

  • 测试实现列在 META-INF/services 文件中

src/main/example/Service.java

public interface Service {
  public static List<Service> loadServices(){
    return StreamSupport.stream(ServiceLoader.load(Service.class).spliterator(),false)                                       
                        .collect(Collectors.toList());
   }
}

和一个src/main/module-info.java

module example {
  uses example.Service;
  exports example;
}

我有一个这样的单元测试

src/main/example/ServiceTest.java

public ServiceTest {
  @Test
  void loadServices_should_find_TestServices{
    List<Service> services = Service.loadServices();
    assertEquals(2, services.size());
  }
}

我在测试源中有两个测试服务:

src/main/example/TestService1.java

public TestService1 implements Service {}

src/main/example/TestService2.java

public TestService2 implements Service {}

src/test/resources/META-INF/services/example.Service

example.TestService1
example.TestService2

我正在使用 maven-surefire-plugin 3.0.0-M3 没有任何特定配置

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-failsafe-plugin</artifactId>
  <version>3.0.0-M3</version>
</plugin>

正确修补示例模块(来自surefireargs文件)

--patch-module example="D:\\git\\example\\target\\test-classes"

当我直接在IntelliJ中执行测试时,测试运行成功,发现两个服务。 但是,当我在 maven 中构建模块并且测试由 surefire 执行时,它没有找到服务并且测试失败。

我应该如何配置surefire以找到位于测试源中的TestServices? 我无法在模块信息中定义“提供...”声明,因为它们是测试服务。 我究竟做错了什么?

我找到了一个解决方法,我并没有真正考虑该问题的实际解决方案:在surefire中禁用ModulePath,恢复到ClassPath:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <configuration>
    <useModulePath>false</useModulePath>
  </configuration>
</plugin>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM