我在课程中有一个标记为@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";
}
如果我写下面的代码:
MockHttpServletRequestBuilder request = MockMvcRequestBuilders
.get("/addEvent");
ResultActions result = mockMvc.perform(request);
result.andExpect(MockMvcResultMatchers.status().isOk());
我明白了:
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$5.match(StatusResultMatchers.java:549)
...
问题是什么,我该如何解决?
更新
如果我写:
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"));
我看到了相同的结果。
分辨
Bitman建议+添加(由Sotirios Delimanolis提供)
request.param("selectedEventTypeId", "1");
request.param("selectedEventStatusId", "1");
在我的情况下,Event事件实例将从Spring中获取什么?
答案 0 :(得分:8)
更改此
MockHttpServletRequestBuilder request = MockMvcRequestBuilders
.get("/addEvent");
到
MockHttpServletRequestBuilder request = MockMvcRequestBuilders
.post("/addEvent");
因为您期望控制器中有method = RequestMethod.POST
POST
但是你的测试正在执行GET。
这是HTTP错误405方法不允许的意思