问题描述
我的 Spring Boot 应用程序在 2.4.2 版上运行。我正在尝试为用户注册设置集成测试。此测试类从定义一些静态设置的 AbstractIntegrationTest
扩展而来。
开始测试时,webTestClient
为 null
。我尝试添加 @AutoConfigureWebTestClient
,但问题仍然存在。
你知道这里可能缺少什么吗?
RegistrationIT.java
public class RegistrationIT extends AbstractIntegrationTest {
@Autowired
private WebTestClient webTestClient;
@Test
public void shouldRegisterNewUser() throws JSONException {
String requestBody; // some JSON
webTestClient
.post()
.uri("/api/user")
.body(BodyInserters.fromValue(requestBody))
.exchange()
.expectStatus().isOk();
}
}
AbstractIntegrationTest.java
@SpringBoottest(webEnvironment = SpringBoottest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("integration-test")
@Testcontainers
public abstract class AbstractIntegrationTest {
private static final String MARIADB_IMAGE_NAME = "mariadb:10.4.16";
private static final String MARIADB_DATABASE_NAME = "test_db";
private static final String MARIADB_USERNAME = "test_user";
private static final String MARIADB_PASSWORD = "test_pass";
static final MariaDBContainer mariaDBContainer = (MariaDBContainer) new MariaDBContainer(MARIADB_IMAGE_NAME)
.withDatabaseName(MARIADB_DATABASE_NAME)
.withUsername(MARIADB_USERNAME)
.withPassword(MARIADB_PASSWORD)
.withReuse(true);
static {
mariaDBContainer.start();
}
@DynamicPropertySource
static void registerProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url",mariaDBContainer::getJdbcUrl);
registry.add("spring.datasource.username",mariaDBContainer::getUsername);
registry.add("spring.datasource.password",mariaDBContainer::getpassword);
}
}
解决方法
调试后,我发现我使用的是 JUnit 4 中的 @Test
批注而不是 JUnit 5。更正 import
语句后,测试运行成功。