java.lang.AssertionError: 预期状态:<200> 但为:<405>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19405806/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java.lang.AssertionError: Status expected:<200> but was:<405>
提问by gstackoverflow
I have a method located in class marked as @Controller
我有一个位于类中的方法标记为 @Controller
@RequestMapping(value = "/addEvent", method = RequestMethod.POST)
public String addEvent(Model model,
@Valid @ModelAttribute("myEvent") Event event,
BindingResult result, RedirectAttributes redirectAttributes,
@RequestParam(required = true) Integer selectedEventTypeId,
@RequestParam(required = true) Integer selectedEventStatusId) {
if (result.getErrorCount() > 1 ){
return "eventDetailsAdd";
}
eventService.addEvent(event, selectedEventTypeId, selectedEventStatusId);
redirectAttributes.addAttribute("idEvent", event.getId());
redirectAttributes.addAttribute("message", "added correctly at " + new Date() );
return "redirect:eventDetails";
}
If I write following code:
如果我编写以下代码:
MockHttpServletRequestBuilder request = MockMvcRequestBuilders
.get("/addEvent");
ResultActions result = mockMvc.perform(request);
result.andExpect(MockMvcResultMatchers.status().isOk());
I see:
我懂了:
java.lang.AssertionError: Status expected:<200> but was:<405>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:60)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:89)
at org.springframework.test.web.servlet.result.StatusResultMatchers.match(StatusResultMatchers.java:549)
...
What's the problem, and how would I fix it?
有什么问题,我该如何解决?
UPDATE
更新
if I write:
如果我写:
MockHttpServletRequestBuilder request = MockMvcRequestBuilders
.get("/addEvent");
request.param("selectedEventTypeId", "1");
request.param("selectedEventStatusId", "1");
ResultActions result = mockMvc.perform(request);
result.andExpect(MockMvcResultMatchers.status().isOk());
result.andExpect(MockMvcResultMatchers.forwardedUrl("eventDetailsAdd"));
I see the same result.
我看到同样的结果。
RESOLVED
解决
Bitman advice + add(by Sotirios Delimanolis)
Bitman 建议 + 添加(由 Sotirios Delimanolis)
request.param("selectedEventTypeId", "1");
request.param("selectedEventStatusId", "1");
What will the Event event instance take from Spring in my case?
在我的情况下,事件事件实例将从 Spring 中获取什么?
采纳答案by Bitman
Change this
改变这个
MockHttpServletRequestBuilder request = MockMvcRequestBuilders
.get("/addEvent");
to
到
MockHttpServletRequestBuilder request = MockMvcRequestBuilders
.post("/addEvent");
Because you're expecting method = RequestMethod.POST
POST in controller
But your test is executing GET.
因为您期望method = RequestMethod.POST
控制器中的 POST 但您的测试正在执行 GET。
This is what HTTP Error 405 Method not allowed means
这就是 HTTP 错误 405 方法不允许的意思