0

我目前写了一个我想通过 WebTestClient 测试的 put 请求。我遵循了一些教程并将我的案例适应了它。测试请求会导致错误:

“NOSuchBeanDefinitionException:没有可用的‘org.springframework.test.web.reactive.server.WebTestClient’类型的合格bean:预计至少有1个符合自动装配候选资格的bean。依赖注释:{@org.springframework.beans.factory.annotation .Autowired(必需=真)}"

我在 SO 上查找了一些解决方案,例如:Cant autowire `WebTestClient` - 没有自动配置,但无法使其工作,尽管有提示。

这是测试代码:

@SpringBootTest
@AutoConfigureWebTestClient
public class DemonstratorApplicationTests {

private P4uServiceImpl p4uService = new P4uServiceImpl();

@Autowired
WebTestClient webTestClient;

@MockBean
ReqP4uAccount account;

@Test
void testPutAccount(){

    ReqP4uAccount request = p4uService.buildRequest("testAccount");

    this.webTestClient.put()
            .uri("/account")
            .contentType(MediaType.APPLICATION_JSON)
            .body(request, ReqP4uAccount.class)
            .exchange()
            .expectStatus().isOk()
            .expectBody(P4uAccount.class);
}
}

有谁知道测试设置有什么问题?提前谢谢

4

1 回答 1

1

以下作品:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-webflux</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureWebTestClient
public class DemoApplicationTests {

    @Autowired
    WebTestClient webTestClient;

如果删除(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)它将失败。


如果您查看 WebTestClientAutoConfiguration ,您会发现它有 @ConditionalOnClass({ WebClient.class, WebTestClient.class }) ,这可能就是它无法工作的原因,除非 Springboot 在期间启动 Web 应用程序上下文(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)

/**
 * Auto-configuration for {@link WebTestClient}.
 *
 * @author Stephane Nicoll
 * @author Andy Wilkinson
 * @since 2.0.0
 */
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ WebClient.class, WebTestClient.class })
@AutoConfigureAfter({ CodecsAutoConfiguration.class, WebFluxAutoConfiguration.class })
@Import(WebTestClientSecurityConfiguration.class)
@EnableConfigurationProperties
public class WebTestClientAutoConfiguration {
于 2022-01-07T14:56:47.377 回答