I have a method located in class marked as @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$5.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)
request.param("selectedEventTypeId", "1");
request.param("selectedEventStatusId", "1");
What will the Event event instance take from Spring in my case?
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.
This is what HTTP Error 405 Method not allowed means
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.