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

设置compileSourceRoots后Maven未执行测试的问题

解决Maven添加生成类目录后测试不执行的问题

你遇到的问题根源在于错误配置了compileSourceRoots:

  • 把src/main/resources加入了编译源码目录,这个目录是用来存放资源文件(如.properties、.xml)的,并非Java源码目录,编译器会尝试编译其中的非Java文件,可能导致潜在的编译异常或类路径混乱。
  • 直接覆盖compileSourceRoots的方式会干扰Maven默认的项目路径配置,间接影响测试阶段对测试类的识别。

方案1:修正compiler插件配置,用add-source添加生成目录

移除错误的src/main/resources配置,改用add-source目标添加生成的源码目录,这样不会覆盖默认的源码路径:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>${compiler-plugin.version}</version>
    <executions>
        <execution>
            <id>add-generated-sources</id>
            <phase>generate-sources</phase>
            <goals>
                <goal>add-source</goal>
            </goals>
            <configuration>
                <sources>
                    <source>${project.build.directory}/generated-sources/openapi/src/gen/java</source>
                </sources>
            </configuration>
        </execution>
    </executions>
</plugin>

方案2:使用build-helper-maven-plugin添加源码目录

这是更通用的添加额外源码目录的方式,不会影响compiler插件的默认配置:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>build-helper-maven-plugin</artifactId>
    <version>3.4.0</version>
    <executions>
        <execution>
            <id>add-generated-source</id>
            <phase>generate-sources</phase>
            <goals>
                <goal>add-source</goal>
            </goals>
            <configuration>
                <sources>
                    <source>${project.build.directory}/generated-sources/openapi/src/gen/java</source>
                </sources>
            </configuration>
        </execution>
    </executions>
</plugin>

额外检查点

  • 确保测试类符合Maven默认命名规则(如*Test.java),如果需要自定义规则,可在maven-surefire-plugin中配置<includes>。
  • 执行mvn clean verify查看完整日志,确认编译阶段无异常,测试类被正确编译。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 17:12:51