Spring Boot 4.x测试:TestRestTemplate的导入无法解析,JUnit 6、Gradle、IntelliJ

后端开发 2026-07-12

我在解析依赖时遇到了问题(例如)

import org.springframework.boot.test.web.client.TestRestTemplate;

下面是我的 build.gradle.kts,关于依赖管理:

plugins {
    java
    alias(libs.plugins.springBoot)
    alias(libs.plugins.springDependencyMngmnt)
    id("idea")
}

configurations {
    compileOnly {
        extendsFrom(configurations.annotationProcessor.get())
    }
}

dependencies {

    implementation(project(":prog1"))
    implementation(project(":prog2"))

    implementation("org.springframework.boot:spring-boot-starter-thymeleaf")
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("org.springframework.boot:spring-boot-starter-security")

    compileOnly("org.projectlombok:lombok")
    annotationProcessor("org.projectlombok:lombok")

    developmentOnly("org.springframework.boot:spring-boot-devtools")


    testImplementation("org.springframework.boot:spring-boot-starter-test")
    testImplementation(platform("org.testcontainers:testcontainers-bom:2.0.3"))
    testImplementation("org.testcontainers:junit-jupiter")
}

tasks.test {
    useJUnitPlatform()
}

版本在 lib.versions.toml 中配置:

[versions]
junitJupiter = "6.0.1"
junitPlatformLauncher = "6.0.1"
springBoot = "4.0.0"
springDependencyMngmnt = "1.1.7"

[libraries]
junitJupiter = { module = "org.junit.jupiter:junit-jupiter", version.ref = "junitJupiter" }
junitPlatformLauncher = { module = "org.junit.platform:junit-platform-launcher", version.ref = "junitPlatformLauncher" }

[plugins]
springBoot = { id = "org.springframework.boot", version.ref = "springBoot"}
springDependencyMngmnt = { id = "io.spring.dependency-management", version.ref = "springDependencyMngmnt"}

我已经反复查找,依赖配置在我看来没问题,但最终并非如此,因为测试类中的类无法正确解析。就应用程序而言,它可以正常运行;只有测试出现问题。

有人能指出问题/冲突可能出在哪里吗?

解决方案

正如之前的帖子所确认的。官方迁移指南的表述如下:“在你的测试中对 TestRestTemplate, 出现编译失败时,添加对 org.springframework.boot:spring-boot-resttestclient'. 的测试作用域依赖”

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章