【问题标题】:Populate context in unit test for webclient在 webclient 的单元测试中填充上下文
【发布时间】:2023-02-22 15:31:12
【问题描述】:

我添加了一个 WebClientCustomizer,它从上下文视图中获取一个值,该值将作为传出请求的标头添加。代码如下所示:

@Override
public void customize(WebClient.Builder builder) {
    builder
        .filter((request, next) ->
                Mono.deferContextual(contextView ->
                    next.exchange(from(request)
                        .header("myHeader", contextView.getOrDefault("id", UUID.randomUUID().toString())).build()
                    )
        ));
}

我想为此创建一个测试,其中 contextView 包含一个预定义的值。我可以使用 MockWebServer 来接收请求,然后我可以从中读取标头。但问题是,我如何在测试中填充反应器上下文?

【问题讨论】:

  • 您如何在应用程序中填充上下文?
  • 使用 WebFilter:return chain.filter(exchange).contextWrite(context -> context.put("id", id));
  • 我的意思是你从哪里得到这个ID?基本上你需要在测试中模拟相同的内容。
  • 传入请求
  • 一定有可能以某种方式向上下文添加虚拟值吗?所以我可以单独测试这个组件

标签: spring spring-webflux project-reactor


【解决方案1】:

您可以使用多种方法来验证此逻辑。

  1. 通过显式提供上下文来隔离测试WebClient。
    @Test
    void test() {
        request() // webclient call
          .contextWrite(context -> context.put("id", "00000"))
          .as(StepVerifier::create)
          .assertNext(res -> {
            // assert results
          })
          .verifyComplete();
    }
    
    1. 此外,您可以使用WebTestClient通过向控制器发送请求来验证流程e2e。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-25
    • 2013-06-25
    • 2018-09-05
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多