无法自动装配`WebTestClient` - 无需自动配置

Mul*_*ard 17 spring spring-boot spring-webflux

我们使用spring framework 5和spring boot 2.0.0.M6,我们也WebClient用于反应式编程.我们为我们的反应式休息端点创建了测试方法,因此我查找了一些关于如何操作的示例.我发现这个或者这个以及许多其他的都是一样的.他们只是自动装配一个WebTestClient.所以我尝试了同样的事情:

@Log
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class MyControllerTest {

    @Autowired
    private WebTestClient webClient;

    @Test
    public void getItems() throws Exception {
        log.info("Test: '/items/get'");

        Parameters params = new Parameters("#s23lkjslökjh12", "2015-09-20/2015-09-27");

        this.webClient.post().uri("/items/get")
                .accept(MediaType.APPLICATION_STREAM_JSON)
                .contentType(MediaType.APPLICATION_STREAM_JSON)
                .body(BodyInserters.fromPublisher(Mono.just(params), Parameters.class))
                .exchange()
                .expectStatus().isOk()
                .expectHeader().contentType(MediaType.APPLICATION_STREAM_JSON)
                .expectBody(Basket.class);
    }
}
Run Code Online (Sandbox Code Playgroud)

我无法运行,因为我收到错误:

Could not autowire. No beans of 'WebTestClient' type found.
Run Code Online (Sandbox Code Playgroud)

因此,似乎不存在自动配置.我使用的是错误版本还是这里有什么问题?

Luk*_*řán 31

使用注释注释您的MyControllerTest测试类@AutoConfigureWebTestClient.那应该解决这个问题.

  • 如果我删除 webEnvironment = WebEnvironment.RANDOM_PORT,我会看到错误“无法自动装配 WebTestClient”。为什么需要它? (4认同)
  • 是的,谢谢.另一个可能的注释是`@WebFluxTest(MyControllerTest.class)` (3认同)
  • 对我没有任何改变。 (3认同)

Xtr*_*ica 23

接受的答案会继续为我抛出这个错误,而不是在Spring Boot 2.0.3中除了测试启动器之外我还要添加webflux启动器:

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

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)

然后使用标准的Web测试注释:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class IntegrationTest {

    @Autowired
    private WebTestClient webClient;

    @Test
    public void test() {
        this.webClient.get().uri("/ui/hello.xhtml")
          .exchange().expectStatus().isOk();
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 依赖项 + `@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)` + `@AutoConfigureWebTestClient` 有效。 (2认同)