You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让公共库/src/test/java下的测试类仅对依赖项目测试可见?

解决公共库测试类跨项目复用问题

这问题我太熟了!Maven默认不会把公共库src/test/java下的代码打包进主依赖包,所以依赖项目的测试代码自然找不到它。要让这个测试类仅对测试场景可见,同时保留在原目录下,分两步操作就行:

1. 在公共库(my-commons)的pom.xml中配置生成测试Jar包

需要用maven-jar-plugin插件生成一个包含src/test/java代码的测试Jar,这样依赖项目才能拉取到测试类。添加以下配置到公共库的<build>节点里:

<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-jar-plugin</artifactId>
      <version>3.3.0</version>
      <executions>
        <execution>
          <goals>
            <goal>test-jar</goal>
          </goals>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>

执行mvn clean install后,公共库会生成两个Jar包:一个是主Jar(my-commons-1.0.0.jar),另一个是测试Jar(my-commons-1.0.0-tests.jar),后者就包含了你放在src/test/java下的TestfileReader类。

2. 在依赖项目中引入测试Jar依赖

除了原有的主依赖,还要额外引入测试Jar的依赖,并且指定scope为test(确保仅在测试阶段生效,不会污染主代码)。修改依赖项目的pom.xml:

<dependencies>
  <!-- 公共库主依赖 -->
  <dependency>
    <groupId>com.myproject</groupId>
    <artifactId>my-commons</artifactId>
    <version>1.0.0</version>
  </dependency>
  <!-- 公共库测试代码依赖 -->
  <dependency>
    <groupId>com.myproject</groupId>
    <artifactId>my-commons</artifactId>
    <version>1.0.0</version>
    <type>test-jar</type>
    <scope>test</scope>
  </dependency>
</dependencies>

这样配置后,依赖项目的SomeTest.java就能正常导入com.myproject.utils.TestfileReader了,而且这个测试类始终只存在于公共库的测试目录下,不会被主代码依赖到。

内容的提问来源于stack exchange,提问作者membersound

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:11:51