【问题标题】:How to input attribute into the webtestclient如何在 webtestclient 中输入属性
【发布时间】:2021-07-05 17:17:43
【问题描述】:

我有一个控制器,它从属性映射中获取一个值。

负责在属性中获取某些东西的代码是这样的:

Map<String, Object> memberClaims = (Map<String, Object>) request.getAttribute("token");

在我的测试中,这就是我的接线方式:

   @Test
   public void shouldReturn200()
   {
      webTestClient.post()
                   .uri(URL)
                   .contentType(MediaType.APPLICATION_JSON)
                   .accept(MediaType.APPLICATION_JSON)
                   .body(Mono.just(order()), Token.class)
                   .attribute("token", "123abc")
                   .exchange()
                   .expectStatus()
                   .is2xxSuccessful();

   }

但 .attribute 似乎没有任何效果。我已经调试过,可以看到令牌映射不在 MockHttpServletRequest.. 因此测试返回 500 服务器响应.. 空指针。

有谁知道我如何为模拟请求添加属性?

【问题讨论】:

    标签: java spring spring-boot mockito


    【解决方案1】:

    您必须知道.attribute(String, String) 并非旨在将来自客户端的参数与请求一起发送。当请求已经在服务器端时,它用于将附加属性添加到请求中。 一个例子是,如果您在 Spring 中有一个拦截器,在获取请求并随后转发请求后添加更多信息。这很好解释here

    要从客户端发送“属性”,您必须将它们添加为参数,如下例所示:

    var respSpec = webTestClient.post()
          .uri( uriBuilder - > uriBuilder
            .scheme("http")
            .host("localhost")
            .port("10080")
            .path("/endpoint")
            .queryParam("requestId", requestId)
            .queryParam("aUrl", aUrl)
            .build())
          .header(apiSecretHeader, secret)
          .header("HEADER_1", "header value 1")
          .header("HEADER_2", "header value 2")
          .exchange();
    

    REST 端点可以这样定义:

    @PostMapping(value = "/endpoint", produces = {MediaType.APPLICATION_JSON_VALUE})
        @ResponseStatus(HttpStatus.ACCEPTED)
        public ResponseEntity<?> myEndpoint(@RequestParam final String requestId, @NonNull @RequestParam(name = "url") final URL aUrl)
    

    【讨论】:

      猜你喜欢
      • 2021-12-30
      • 2018-10-28
      • 1970-01-01
      • 2022-08-15
      • 2012-01-07
      • 2013-07-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多