spring-boot-maven-plugin运行测试包主类报ClassNotFoundException如何解决?
解决测试包SpringBootApplication启动时的ClassNotFoundException问题
出现该错误的核心原因:默认情况下spring-boot-maven-plugin的start/stop目标仅扫描主源码目录(src/main/java)编译后的类,测试目录(src/test/java)的类不在其默认类路径范围内,因此找不到指定的ApplicationTestMode类。
你需要修改插件配置,让它加载测试类并使用测试类路径,具体配置如下:
<plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <mainClass>launchers.ApplicationTestMode</mainClass> <!-- 指定测试类编译后的输出目录 --> <classesDirectory>${project.build.testOutputDirectory}</classesDirectory> <!-- 启用测试类路径,包含测试依赖 --> <useTestClasspath>true</useTestClasspath> </configuration> <executions> <!-- 集成测试前启动应用 --> <execution> <id>start-test-app</id> <phase>pre-integration-test</phase> <goals> <goal>start</goal> </goals> </execution> <!-- 集成测试完成后停止应用 --> <execution> <id>stop-test-app</id> <phase>post-integration-test</phase> <goals> <goal>stop</goal> </goals> </execution> </executions> </plugin>
关键配置说明
<classesDirectory>:指定插件加载类的目录为测试类编译输出目录(默认是target/test-classes),确保插件能找到测试包里的启动类。<useTestClasspath>:设置为true后,插件会包含项目的测试依赖和测试类路径,避免运行时缺少测试相关依赖。- 阶段绑定:将start/stop目标分别绑定到
pre-integration-test和post-integration-test阶段,执行mvn verify时会自动完成应用启动、集成测试运行、应用停止的流程。
额外注意事项
- 先执行
mvn test-compile确保测试类已编译到target/test-classes目录,再执行启动命令。 - 确认
ApplicationTestMode类的包路径与配置中的mainClass完全一致,避免拼写错误。
内容的提问来源于stack exchange,提问作者EE AA
相关产品推荐
相关产品推荐

