Java 405测试spring应用程序时不支持请求方法“POST”
我准备并扩展了这个运行良好的程序。您只需使用user和密码登录,然后就可以转发到user/index 使用此控制器Java 405测试spring应用程序时不支持请求方法“POST”,java,spring-mvc,spring-boot,htmlunit,spring-mvc-test,Java,Spring Mvc,Spring Boot,Htmlunit,Spring Mvc Test,我准备并扩展了这个运行良好的程序。您只需使用user和密码登录,然后就可以转发到user/index 使用此控制器 @Controller public class LoginController { @GetMapping("/login") public String login() { return "login"; } @GetMapping("/login-error") public String loginError(Mod
@Controller
public class LoginController {
@GetMapping("/login")
public String login() {
return "login";
}
@GetMapping("/login-error")
public String loginError(Model model) {
model.addAttribute("loginError", true);
return "login";
}
}
但是,当我运行使用WebClient的示例测试时,相同的登录导致了异常:
com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException: 405 Request method 'POST' not supported for http://localhost:8080/login
这很奇怪,因为应用程序本身工作正常
编辑:这是导致问题的测试方法
@And("^the user clicks the login button$")
public void theUserClicksTheLoginButton() throws IOException {
page = page.getElementById("login").click();
}
我没想到WebClient的click方法使用POST,而不是真正执行html中的输入字段
<form th:action="@{/login}" method="post">
<label for="username">Username</label>:
<input type="text" id="username" name="username" autofocus="autofocus" /> <br />
<label for="password">Password</label>:
<input type="password" id="password" name="password" /> <br />
<input type="submit" id="login" value="Log in" />
</form>
编辑2:
好的,梅比,我想请克拉利回答一下我的问题。
我知道登录应该通过POST完成,我的@Controller只提供@GetMapping,但这没问题,因为spring security正在处理POST请求,正如我在登录时在标题中看到的那样:
我的问题是,为什么它在运行应用程序时工作正常,为什么在使用WebClient时没有相同的行为。web客户端通过POST请求调用服务,这导致了异常:请求方法“POST”不受支持。服务端看起来不错。我不太熟悉如何使用Cucumber设置Spring,我不确定是否要将SpringRunner和Cumber跑步者混合在同一个设置中 我更新了您的测试设置,如下所示:
@RunWith(SpringRunner.class)
@WebMvcTest
@ContextConfiguration
@Import(SecurityConfig.class)
public class LoginFeatureStepDefinition {
private String username;
private String password;
private HtmlPage page;
@Autowired
private WebClient webDriver;
我已经用@WebMvcTest替换了@SpringBootTest,因为mockmvc自动配置将为您处理webclient设置。如果您想用整个应用程序启动一个实际的服务器,并用HTTP客户机对其进行测试,则需要设置@SpringBootTest。
在MockMvc设置中,默认情况下不会导入安全配置,因此需要导入它
是的,我也从例外中意识到。问题是如何执行登录,使其工作方式与实际用户单击登录时一样。请尝试将映射更改为@postmappingthat,这不是我想要的。我试图理解为什么当一个真正的用户点击@Postmapping时并不需要它,而WebClient需要它。这种行为对我来说没有意义,我希望有同样的行为。->它永远不会到达get映射,因为UI方法是POST。您得到的异常是正确的,也是预期的。GET应用于检索数据。我们只能通过URL或请求头发送参数。POST用于将数据发送到服务器。提交表格只能通过邮寄方式完成。用户名和密码不应通过URL参数发送,而应通过请求正文发送。是的,我完全同意你的意见,但这不是我的问题。我编辑了我的帖子,希望能让我的问题更清楚一点。你使用Spring安全性吗?是的,我使用->查看build.gradle和org.springframework.Security.samples.config.SecurityConfigSpring安全性提供了一个登录控制器,可以通过覆盖configureHttpSecurity http方法来设置。这应该在测试中完成让应用程序的运行方式与正常运行应用程序的运行方式相同的目的?这在SecurityConfig.java中是done