gstackoverflow gstackoverflow - 5 months ago 26
Java Question

java.lang.AssertionError: Status expected:<200> but was:<405>

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?

Answer

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