Программирование

Spring Boot 4: фикс @AutoConfigureWebTestClient в test fixtures

Как исправить ошибку unresolved @AutoConfigureWebTestClient в Spring Boot 4.0 с Gradle, Kotlin и test fixtures. Правильные зависимости spring-boot-webtestclient, обновление импортов и пример build.gradle.kts для тестов WebTestClient.

Spring Boot 4.0.0 can’t find @AutoConfigureWebTestClient – how do I fix the missing dependency when using Kotlin, Gradle, and test fixtures?

I upgraded a Spring Boot project from 3.5 to 4.0 and now the annotation @AutoConfigureWebTestClient is unresolved in my reusable composite test class annotation that lives in testFixtures. Both the new package org.springframework.boot.webtestclient.autoconfigure and the old org.springframework.boot.test.autoconfigure.web.reactive are missing.

I’ve added spring-boot-starter-test as a testImplementation dependency and spring-boot-starter-webclient-test as a testFixturesCompileOnly (and also tried testFixturesImplementation). The build.gradle.kts looks like this:

kotlin
plugins {
 `java-test-fixtures`
}
...
dependencies {
 testImplementation("org.springframework.boot:spring-boot-starter-test:4.0.0")
 testFixturesCompileOnly("org.springframework.boot:spring-boot-starter-webclient-test:4.0.0")
 ...
}

The annotation class is defined as:

kotlin
import org.springframework.boot.autoconfigure.EnableAutoConfiguration
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.ActiveProfiles
import org.springframework.boot.webtestclient.autoconfigure.AutoConfigureWebTestClient
import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient

@SpringBootTest
@EnableAutoConfiguration
@AutoConfigureWebTestClient
@ActiveProfiles("sandbox", "debug", "nodb")
annotation class TestWithoutDb

What’s the correct way to include the webclient-test dependency so that @AutoConfigureWebTestClient is available in test fixtures with Spring Boot 4.0.0?

В Spring Boot 4.0 аннотация @AutoConfigureWebTestClient переместилась в модульный артефакт spring-boot-webtestclient, который больше не транзитивно подключается через spring-boot-starter-test. Для test fixtures в Gradle с Kotlin используйте testFixturesImplementation("org.springframework.boot:spring-boot-webtestclient:4.0.0") вместо compileOnly, и обновите импорт на org.springframework.boot.webtestclient.autoconfigure.AutoConfigureWebTestClient. Это решит проблему с unresolved annotation в композитных тестах, как подтверждают официальные issues Spring.


Содержание


Что изменилось в Spring Boot 4.0 для тестирования

Spring Boot 4.0 ввел модульную структуру, где многие автоконфигурации, включая WebTestClient, вынесены в отдельные стартеры. Раньше @AutoConfigureWebTestClient тянулся автоматически через spring-boot-starter-test, но теперь это не так — нужно явно добавлять spring-boot-webtestclient. Почему? Команда Spring разбила монолитные зависимости, чтобы проекты компилировались быстрее и без лишнего.

Представьте: ваш тест падает с ошибкой “Type org.springframework.boot.webtestclient.autoconfigure.AutoConfigureWebTestClient not present”. Это классика апгрейда с 3.x. В issue #47414 прямо пишут о смене FQCN (полного имени класса) и пакета — старый путь org.springframework.boot.test.autoconfigure.web.reactive устарел. А в другом тикете обсуждают, как отсутствие codec-зависимостей ломает автоконфиг.

Но хорошие новости: фикс простой. Добавьте зависимость, обновите импорт — и spring boot test полетит. Это особенно актуально для реактивных стеков с WebFlux.


Правильная настройка зависимостей Gradle

В spring boot gradle проектах для spring boot 4 базовая spring-boot-starter-test покрывает JUnit и Mockito, но не WebTestClient. Добавьте:

kotlin
dependencies {
 testImplementation("org.springframework.boot:spring-boot-starter-test:4.0.0")
 testImplementation("org.springframework.boot:spring-boot-webtestclient:4.0.0") // Для обычных тестов
}

Обратите внимание: не spring-boot-starter-webclient-test (это выдуманное имя), а именно spring-boot-webtestclient. Подтверждение из issue #2087: проверьте jar-файл, там класс в автоконфиге именно оттуда.

Для spring boot kotlin это работает идеально — Gradle Kotlin DSL понимает SNAPSHOT’ы, если нужно. После ./gradlew clean build аннотация разрешится. А если используете testcontainers spring boot, то WebTestClient интегрируется без проблем.


Обновление импортов и аннотаций

В вашем композитном анноте @TestWithoutDb удалите старый импорт:

kotlin
// ❌ Удалить
import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient

// ✅ Добавить
import org.springframework.boot.webtestclient.autoconfigure.AutoConfigureWebTestClient

Новый путь — org.springframework.boot.webtestclient.autoconfigure.AutoConfigureWebTestClient. Issue #47892 жалуется на несоответствие пакетов, но в 4.0.0 это пофиксили. Теперь автоконфиг для webtestclient лежит в autoconfigure-пакете, как и положено.

Если тест на WebFlux, добавьте @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT). Пример из блога по Spring Boot 4:

kotlin
@Autowired
private lateinit var webTestClient: WebTestClient

@Test
fun `get user returns details`() {
 webTestClient.get().uri("/users/1")
 .exchange()
 .expectStatus().isOk
}

Коротко и мощно. Не забудьте @AutoConfigureWebTestClient сверху.


Настройка test fixtures в Kotlin

Вот где засада для gradle test fixtures. testFixturesCompileOnly не тянет транзитивы — компилятор видит класс, но на runtime может упасть. Меняйте на testFixturesImplementation:

kotlin
plugins {
 `java-test-fixtures`
}

dependencies {
 testImplementation("org.springframework.boot:spring-boot-starter-test:4.0.0")
 testFixturesImplementation("org.springframework.boot:spring-boot-webtestclient:4.0.0")
}

В Spring AI issue #4948 советуют именно так для модульных стартеров. Для Kotlin MPP или мультимодульных проектов — testFixturesImplementation в build.gradle.kts subproject’а с fixtures. После gradle test в consuming модулях аннотация из fixtures подхватится.

Почему не compileOnly? Потому что fixtures — это shared код, и IDE (IntelliJ) требует полного classpath. Плюс, в CI без кэша Maven/Gradle это спасет от “cannot resolve import”.


Полный пример build.gradle.kts

Вот рабочий build.gradle.kts для вашего случая:

kotlin
plugins {
 kotlin("jvm") version "2.0.0"
 id("org.springframework.boot") version "4.0.0"
 id("io.spring.dependency-management") version "1.1.6"
 `java-test-fixtures`
}

dependencies {
 implementation("org.springframework.boot:spring-boot-starter-webflux")
 testImplementation("org.springframework.boot:spring-boot-starter-test")
 testFixturesImplementation("org.springframework.boot:spring-boot-webtestclient:4.0.0")
 testFixturesImplementation("org.springframework.boot:spring-boot-starter-test:4.0.0") // Опционально, для полноты
}

tasks.test {
 useJUnitPlatform()
}

Запустите ./gradlew clean build testFixturesJar. В fixtures-модуле @AutoConfigureWebTestClient теперь компилируется. Пример из Medium подтверждает: с RANDOM_PORT это идеально для spring boot integration tests.


Частые ошибки и отладка

  • Ошибка “CodecCustomizer not present”: Добавьте spring-boot-http-codec или исключите WebTestClientAutoConfiguration через excludeAutoConfiguration.
  • Snapshot-зависимости: Используйте 4.0.0-M3+ из repo.spring.io.
  • IDE не видит: ./gradlew --refresh-dependencies + Reimport Gradle.
  • Runtime fail: Проверьте gradle dependencies --configuration testFixturesRuntimeClasspath.

Если все равно не работает, гляньте issue #46678 — там workaround с @WebMvcTest(excludeAutoConfiguration = ...). Но с правильной зависимостью не понадобится.


Источники

  1. WebClientAutoConfiguration is no longer included by @AutoConfigureWebClient
  2. The import org.springframework.boot.webtestclient.AutoConfigureWebTestClient cannot be resolved
  3. WebTestClientAutoConfiguration fails when WebFlux is on the classpath
  4. Auto-configuration for WebTestClient should be in an autoconfigure package
  5. WebTestClient vs MockMvc in Spring Boot
  6. What’s New for Testing in Spring Boot 4 and Spring Framework 7
  7. Spring Boot 4.0 starters including WebClient and REST client dependencies

Заключение

Переход на Spring Boot 4 с test fixtures в Gradle — это про явные зависимости: testFixturesImplementation("org.springframework.boot:spring-boot-webtestclient:4.0.0") + новый импорт org.springframework.boot.webtestclient.autoconfigure.AutoConfigureWebTestClient. Теперь ваши spring boot test компилируются без ошибок, а webtestclient готов к интеграционным тестам. Протестируйте на чистом билде — и вперед, к реактивным эндпоинтам. Если трафик spike’нет, контейнеры выдержат!

Авторы
Проверено модерацией
Модерация
Spring Boot 4: фикс @AutoConfigureWebTestClient в test fixtures