Как подключить @AutoConfigureWebTestClient в Spring Boot 4
В Spring Boot 4.0.0 аннотация @AutoConfigureWebTestClient перемещена в spring-boot-test-autoconfigure. Добавьте её в testFixtures как implementation.
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:
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:
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?
The annotation was never removed – it was moved out of the test starter and into the standalone test‑autoconfigure module that Spring Boot 4 now ships with.
Because test fixtures are compiled with a separate class‑path, they don’t see the transitive dependencies that spring‑boot‑starter‑test pulls in for your regular test sources.
Add the test‑autoconfigure module explicitly to the test‑fixtures configuration (use implementation, not compileOnly) and the @AutoConfigureWebTestClient annotation will be available.
Содержание
- Проблема и её причины
- Как Spring Boot 4.0 организует тестовые зависимости
- Правильное подключение в Gradle kts
- Проверка и пример использования
- Заключение
Проблема и её причины
@AutoConfigureWebTestClient — аннотация, которая находится в пакете
org.springframework.boot.test.autoconfigure.web.reactive.
В Spring Boot 4.0 этот пакет не входит в spring-boot-starter-test включительно;
он вынесен в отдельный артефакт spring-boot-test-autoconfigure.
Когда вы объявляете зависимость как testFixturesCompileOnly, Gradle не добавляет
перехватываемые транзитивные зависимости, поэтому аннотация остаётся
неразрешённой.
Как Spring Boot 4.0 организует тестовые зависимости
spring-boot-starter-testсодержит только общие тестовые библиотеки и
самspring-boot-test-autoconfigureкак зависимость.spring-boot-test-autoconfigureсодержит аннотации автоконфигурации,
включая@AutoConfigureWebTestClient— https://docs.spring.io/spring-boot/docs/4.0.0.RELEASE/api/org/springframework/boot/test/autoconfigure/web/reactive/AutoConfigureWebTestClient.html.- Для test‑fixtures Gradle требует явного указания зависимостей,
которые должны попасть в их собственный class‑path
(https://docs.gradle.org/current/userguide/java_testing.html#test-fixtures).
Правильное подключение в Gradle kts
plugins {
`java-test-fixtures`
}
dependencies {
// Основные тестовые зависимости – включают test‑autoconfigure
testImplementation("org.springframework.boot:spring-boot-starter-test:4.0.0")
// Добавляем test‑autoconfigure в test‑fixtures
testFixturesImplementation("org.springframework.boot:spring-boot-test-autoconfigure:4.0.0")
// (Опционально) Если нужен только WebClient‑специфический автоконфиг
// testFixturesImplementation("org.springframework.boot:spring-boot-test-autoconfigure:webclient")
}
Важно – используйте
implementation, а неcompileOnly.
compileOnlyподключает только сам модуль, но не его транзитивные зависимости,
которые в нашем случае необходимы для автоконфигурации.
Проверка и пример использования
-
Скомпилируйте проект – Gradle подтянет
spring-boot-test-autoconfigure
в class‑pathtestFixtures. -
Создайте в
src/testFixtures/kotlinфайл:kotlinimport org.springframework.boot.autoconfigure.EnableAutoConfiguration import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.context.ActiveProfiles import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient @SpringBootTest @EnableAutoConfiguration @AutoConfigureWebTestClient @ActiveProfiles("sandbox", "debug", "nodb") annotation class TestWithoutDb -
В обычных тестах импортируйте
TestWithoutDbизtestFixturesи
убедитесь, чтоWebTestClientавтоматически создаётся и вы можете его использовать.
Заключение
@AutoConfigureWebTestClientне исчезла в Spring Boot 4.0; она переместилась вspring-boot-test-autoconfigure.- Для test‑fixtures подключайте этот артефакт как
testFixturesImplementation. - Не используйте
compileOnly; иначе транзитивные зависимости (и сама аннотация) не будут доступны. - После исправления
build.gradle.ktsвы сможете использовать
@AutoConfigureWebTestClientв своих тестовых фикстурах без ошибок класса.
Если вы всё ещё видите ошибку, проверьте, что версия
spring-boot-test-autoconfigureсовпадает с версией Spring Boot 4.0.0, и очистите кэш Gradle (./gradlew clean build --refresh-dependencies).