【问题标题】:Cant autowire `WebTestClient` - no auto configuration无法自动装配`WebTestClient` - 没有自动配置
【发布时间】:2018-06-21 22:32:08
【问题描述】:

我们正在使用 spring 框架 5 和 spring boot 2.0.0.M6,我们还使用 WebClient 进行响应式编程。我们为我们的反应式休息端点创建了测试方法,因此我查找了一些有关如何执行此操作的示例。我发现this 一个或this 和许多其他的都一样。他们只是自动连接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);
    }
}

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

Could not autowire. No beans of 'WebTestClient' type found.

所以似乎不存在自动配置。是我用错了版本还是怎么回事?

【问题讨论】:

    标签: spring spring-boot spring-webflux


    【解决方案1】:

    使用@AutoConfigureWebTestClient 注释来注释您的MyControllerTest 测试类。这应该可以解决问题。

    【讨论】:

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

    接受的答案不断为我抛出该错误,相反,除了 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>
    

    然后使用标准的 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();
        }
    
    }
    

    【讨论】:

    • 在使用 junit 5 运行时仍然对我不起作用......同样的异常。但部门就像这里一样。
    • @ses,你能问一个关于你的案子的问题吗?
    • 依赖 + @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) + @AutoConfigureWebTestClient 工作。
    猜你喜欢
    • 2019-10-21
    • 2019-06-14
    • 2021-08-17
    • 1970-01-01
    • 2020-06-03
    • 1970-01-01
    • 1970-01-01
    • 2016-10-09
    • 2017-08-08
    相关资源
    最近更新 更多