【问题标题】:Java 9: ServiceLoader doesn't load Test implementation from Test sources (Module)Java 9:ServiceLoader 不会从测试源(模块)加载测试实现
【发布时间】:2019-01-08 07:28:09
【问题描述】:

我使用的是Java9 Module系统(在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?我无法在模块信息中定义“提供...”声明,因为它们是测试服务。我究竟做错了什么?

【问题讨论】:

  • 要测试 TestService1 和 TestService2 需要使用适当的 provides 子句将它们放入自己的测试模块中。 JDK 没有--add-provides 选项来扩充模块提供的服务集。因为服务绑定是解决方案的一部分,并且在处理增强模块图的命令行选项之前很久就完成了,所以有这样的选项。
  • 顺便看看 ServiceLoader::stream 方法,这应该将您的代码片段减少到:ServiceLoader.load(Service.class).stream().collect(Collectors.toList());

标签: java unit-testing java-9 serviceloader module-info


【解决方案1】:

我找到了一种解决方法,但我并没有真正考虑解决问题的实际方法: 在万无一失中禁用 ModulePath,恢复为 ClassPath:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-10
    • 2018-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多