使用WebTestClient
的(黄瓜)BDD单元测试失败(禁止403)。经过一些调试后,我确定这是因为CSRF检查失败。但是我的测试步骤似乎是设置CSRF令牌。那么怎么了?如何为WebTestClient
测试设置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",
"/");
}
...
答案 0 :(得分:0)
尽管其名称,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());
}