【问题标题】:WebTestClient mutateWith apparently not mutatingWebTestClient mutateWith 显然没有变异
【发布时间】:2019-03-24 17:24:58
【问题描述】:

我使用WebTestClient 的(黄瓜)BDD 单元测试失败(带有 403 Forbidden),但我认为它应该通过。经过一些调试,我确定这是因为 CSRF 检查失败,这表明 mutateWith(csrf()) 操作不起作用。我做错了什么?


我的测试场景:

  Scenario Outline: Login
    Given that player "<player>" exists with  password "<password>"
    And presenting a valid CSRF token
    When log in as "<player>" using password "<password>"
    Then program accepts the login

我的测试步骤代码(注意client.mutateWith(csrf())的存在):


@SpringBootTest(...)
@AutoConfigureWebTestClient
public class WebSteps {

   @Autowired
   private WebTestClient client;

...

   private WebTestClient.ResponseSpec response;

   @Given("presenting a valid CSRF token")
   public void presenting_a_valid_CSRF_token() {
      client.mutateWith(csrf());
   }

   @When("log in as {string} using password {string}")
   public void log_in_as_using_password(final String player,
            final String password) {
      response = client.post().uri("/login")
               .contentType(MediaType.APPLICATION_FORM_URLENCODED)
               .body(BodyInserters.fromFormData("username", player)
                        .with("password", password))
               .exchange();
   }

   @Then("program accepts the login")
   public void program_accepts_the_login() {
      response.expectStatus().isFound().expectHeader().valueEquals("Location",
               "/");
   }

...

【问题讨论】:

标签: csrf spring-webflux spring-test cucumber-jvm


【解决方案1】:

尽管有它的名字,mutateWith() 方法并没有真正改变它的对象。相反,它返回一个已应用突变的新对象。因此,而不是写

   @Given("presenting a valid CSRF token")
   public void presenting_a_valid_CSRF_token() {
      client.mutateWith(csrf());
   }

写

   @Given("presenting a valid CSRF token")
   public void presenting_a_valid_CSRF_token() {
      client = client.mutateWith(csrf());
   }

由于测试步骤更改共享状态(client 对象)的方式,而不是使用具有长调用链的流畅 API,因此该错误更有可能发生在 Cucumber 测试中。

【讨论】:

    猜你喜欢
    • 2020-03-28
    • 1970-01-01
    • 1970-01-01
    • 2018-06-21
    • 1970-01-01
    • 2020-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多