我有控制器:
@Controller
public class EventMenuController{
@RequestMapping(value = "/updateEvent", method = RequestMethod.POST)
public String updateEvent(Model model,
@Valid @ModelAttribute("existedEvent") Event event,
BindingResult result,
@ModelAttribute("linkedCandidates") Set<Candidate> candidates,
@ModelAttribute("linkedvacancies") Set<Vacancy> vacancies,
@RequestParam(required = true, value = "selectedEventStatusId")Integer EventStatusId,
@RequestParam(required = true, value = "selectedEventTypeId")Integer EventTypeId ,
RedirectAttributes attributes) {
if (result.hasErrors()) {
//model.addAttribute("idEvent", event.getId());
event.setCandidates(candidates);
event.setVacancies(vacancies);
return "eventDetails";
}
eventService.updateEventAndLinkedEntities(event, candidates, vacancies ,EventTypeId,EventStatusId);
attributes.addAttribute("idEvent",event.getId() );//event is null therefore NPE here
attributes.addAttribute("message", "submitted correctly at "+new Date());
return "redirect:eventDetails";
}
}
为了测试这种方法,我编写了以下类:
@ContextConfiguration(locations = { "classpath:/test/BeanConfigUI.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
public class EventMenuControllerTest {
@Test
public void updateEvent() throws Exception{
MockHttpServletRequestBuilder request = MockMvcRequestBuilders
.post("/updateEvent");
request.param("selectedEventStatusId", "1");
request.param("selectedEventTypeId", "1");
EventMenuController eventMenuController = (EventMenuController) wac.getBean("eventMenuController");
EventService mockEventService = Mockito.mock(EventService.class);
eventMenuController.eventService = mockEventService;
Mockito.doNothing().when(mockEventService).updateEventAndLinkedEntities(any(Event.class), any(Set.class),any(Set.class), any(Integer.class), any(Integer.class));
ResultActions result = mockMvc.perform(request);
result.andExpect(MockMvcResultMatchers.view().name("redirect:eventDetails"));
result.andExpect(MockMvcResultMatchers.model().attributeExists("idEvent"));
result.andExpect(MockMvcResultMatchers.model().attributeExists("message"));
}
}
在服务器端执行的进程请求中,我看到错误显示事件对象为空。
问题:
我必须使用 MockMvc 将传递事件写入服务器端(控制器方法)的什么请求?