WebTestClient is null when autowired in a @SpringBootTest

1.1k views Asked by At

My Spring Boot application runs on version 2.4.2. I'm trying to setup an integration test for a user registration. This test class extends from the AbstractIntegrationTest which defines some static setup.

When starting the test, webTestClient is null. I tried to add @AutoConfigureWebTestClient but the issue remains.

Do you have any idea what could be missing here?

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);
    }
}
1

There are 1 answers

0
Robert Strauch On BEST ANSWER

After debugging, I discovered that I used the @Test annotation from JUnit 4 instead of JUnit 5. After having correct the import statement, the test runs successfully.