我有一个方法位于标记为的类中@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 中获取什么?