Spring Boot 3+Java17:IntelliJ测试通过Maven构建测试失败排查
问题分析与解决:Maven构建时测试请求连接被拒绝
问题描述
基于Spring Boot 3 + Java 17的项目中,单元/集成测试使用Surefire插件,尝试通过http://localhost:8081/myfile.xml访问test/resources/static下的文件。在IntelliJ中执行"运行所有测试"时正常通过,但执行mvn clean install时抛出:
ResourceAccessException: I/O error on GET request for "http://localhost:8081/myfile.xml": Connection refused
当前测试类注解:
@ExtendWith(SpringExtension.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT, properties = { "server.port=8080" }) @DirtiesContext
pom.xml相关配置:
<plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> <printSummary>false</printSummary> <redirectTestOutputToFile>true</redirectTestOutputToFile> <argLine>${surefireArgLine} -Xmx1024m -noverify</argLine> </configuration> </plugin>
原因分析
- 端口配置不匹配:测试代码请求的是8081端口,但
@SpringBootTest注解明确指定应用启动在8080端口。IntelliJ运行时可能读取了IDE层面的自定义Run Configuration(比如手动修改过端口),导致应用实际启动在8081,测试能正常访问;而Maven构建时严格遵循注解内的配置启动应用,请求8081自然会被拒绝。 - 测试执行环境差异:IntelliJ的测试运行逻辑会加载项目内的多种配置(包括IDE自定义设置),而Maven的Surefire插件仅严格遵循pom.xml和测试类注解的配置,两者环境不一致导致结果不同。
解决方案
方案1:统一端口配置
将测试请求的端口与注解中指定的端口保持一致,二选一即可:
- 修改注解中的端口为8081:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT, properties = { "server.port=8081" }) - 或者修改测试代码中的请求URL为
http://localhost:8080/myfile.xml
方案2:使用随机端口(推荐)
避免固定端口带来的冲突问题,改用随机端口并动态注入:
@ExtendWith(SpringExtension.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @DirtiesContext public class YourTestClass { @LocalServerPort private int serverPort; // 动态生成请求地址 private String getFileUrl() { return String.format("http://localhost:%d/myfile.xml", serverPort); } // 测试方法中调用getFileUrl()发起请求 }
方案3:确保插件版本适配
Spring Boot 3和Java 17需要对应版本的Maven插件支持,建议在pom.xml中指定插件版本:
<plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>3.2.0</version> <!-- 替换为你的Spring Boot实际版本 --> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.2.5</version> <!-- 适配Java 17的稳定版本 --> <configuration> <printSummary>false</printSummary> <redirectTestOutputToFile>true</redirectTestOutputToFile> <argLine>${surefireArgLine} -Xmx1024m -noverify</argLine> </configuration> </plugin>
内容的提问来源于stack exchange,提问作者Jeiko_1522
相关产品推荐
相关产品推荐

