405请求方法' POST'测试spring应用程序

时间:2018-05-30 20:17:45

标签: java spring-mvc spring-boot htmlunit spring-mvc-test

我准备并扩展了这个运行良好的existing spring example。您只需使用" user"和#34;密码"然后转发到user / index。

使用此控制器

@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安全正在处理POST请求,因为我在登录时可以在标题中看到:

enter image description here

我的问题是为什么它在运行应用程序时运行良好,而为什么在使用WebClient时没有相同的行为

2 个答案:

答案 0 :(得分:2)

我不太熟悉使用Cucumber设置Spring,并且我不确定在同一设置中混合使用SpringRunnerCucumber跑步者。

我已经更新了您的测试设置:

@RunWith(SpringRunner.class)
@WebMvcTest
@ContextConfiguration
@Import(SecurityConfig.class)
public class LoginFeatureStepDefinition {
    private String username;
    private String password;
    private HtmlPage page;

    @Autowired
    private WebClient webDriver;
  1. 我已将@SpringBootTest替换为@WebMvcTest,因为mockmvc自动配置将为您处理webclient设置。如果您想使用整个应用程序启动实际服务器并使用HTTP客户端对其进行测试,则需要设置@SpringBootTest in a different way
  2. 在MockMvc设置中,默认情况下不会导入安全配置,因此您需要导入它

答案 1 :(得分:-1)

Web客户端正在通过POST请求调用该服务,这导致异常:Request method 'POST' not supported。服务端看起来不错。

相关问题