You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Spring Boot 2.0.0.M6中无法自动装配WebTestClient的问题求助

解决Spring Boot 2.0.0.M6中WebTestClient无法自动装配的问题

你遇到的这个问题确实和使用的Spring Boot版本有关——Spring Boot 2.0.0.M6属于早期里程碑版本,当时WebTestClient的自动配置逻辑还未完全完善,容器里没有自动生成对应的Bean,所以@Autowired会失败。下面给你几个可行的解决方案:

方案1:手动创建WebTestClient实例

在测试类里,通过绑定到服务器或者应用上下文手动构建WebTestClient,有两种常用方式:

方式A:绑定到随机端口的服务器

利用@LocalServerPort获取随机端口,直接绑定到运行的服务器:

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

    @LocalServerPort
    private int port;

    @Before
    public void setUp() {
        this.webClient = WebTestClient.bindToServer()
                .baseUrl("http://localhost:" + port)
                .build();
    }

    // 你的测试方法保持不变
    @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);
    }
}

方式B:绑定到应用上下文

直接绑定到Spring应用上下文,不需要依赖外部端口:

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

    @Autowired
    private ApplicationContext context;

    @Before
    public void setUp() {
        this.webClient = WebTestClient.bindToApplicationContext(context)
                .build();
    }

    // 测试方法同上
}

方案2:升级Spring Boot版本

最彻底的解决方式是升级到Spring Boot 2.0.0正式版(或更高版本),后续版本已经完善了WebTestClient的自动配置逻辑,只要使用@SpringBootTest并指定web环境,就能直接@Autowired获取WebTestClient实例,不需要额外配置。

方案3:尝试使用@AutoConfigureWebTestClient注解

如果不想升级版本,可以尝试在测试类上添加@AutoConfigureWebTestClient注解,它的作用是触发WebTestClient的自动配置:

@Log
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@AutoConfigureWebTestClient
public class MyControllerTest {
    @Autowired
    private WebTestClient webClient;

    // 测试方法同上
}

不过需要注意:这个注解在Spring Boot 2.0.0.M6中可能还未完全生效,因为它是后续版本才稳定下来的配置注解,所以优先推荐前两个方案。

内容的提问来源于stack exchange,提问作者Mulgard

火山引擎 最新活动