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

如何用Maven运行Spring Boot 3.2测试类中的main方法?

如何通过Maven命令行启动测试作用域中带TestBootstrap配置的Spring Boot应用

Spring Boot 3.2允许从测试作用域定义的main方法启动应用,示例代码如下:

TestBootstrap配置类:

@TestConfiguration(proxyBeanMethods = false)
class TestBootstrap {

    @Bean
    @ServiceConnection
    @RestartScope
    fun mongoDbContainer() = MongoDBContainer("mongo:4.2.8")
}

测试作用域的main方法:

fun main(args: Array<String>) {
    fromApplication<Bootstrap>().with(TestBootstrap::class).run(*args)
}

默认执行mvn spring-boot:run时,会运行主代码目录下Bootstrap类的main方法,无法加载测试作用域的TestBootstrap配置,也就无法启动Docker容器。要运行测试作用域中加载该配置的main方法,可通过以下两种方式实现:

方法一:通过spring-boot:run指定主类并使用测试类路径

直接在命令行中指定测试main类的全限定名,同时指定使用测试类路径:

mvn spring-boot:run -Dspring-boot.run.main-class=你的测试main类全限定名 -Dspring-boot.run.classpath=test

如果需要固定配置,也可以在pom.xml的Spring Boot Maven插件中预先设置:

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <mainClass>你的测试main类全限定名</mainClass>
        <classpath>test</classpath>
    </configuration>
</plugin>

配置完成后,直接执行mvn spring-boot:run即可启动目标应用。

方法二:使用Spring Boot 3.2+新增的spring-boot:test-run目标

Spring Boot 3.2为Maven插件新增了test-run目标,专门用于基于测试类路径运行应用,无需额外配置类路径参数:

mvn spring-boot:test-run -Dspring-boot.test-run.main-class=你的测试main类全限定名

注意事项

  • 确保测试main类位于测试代码目录(如src/test/kotlin或src/test/java)下
  • 测试依赖(如Testcontainers相关依赖)需正确声明在test作用域中
  • 替换命令和配置中的你的测试main类全限定名为实际类的完整路径(比如com.example.demo.TestApplicationKt)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 13:41:03