1

我有控制器:

@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 将传递事件写入服务器端(控制器方法)的什么请求?

4

1 回答 1

0

Event对象未初始化。您可以根据测试用例创建Event对象或创建对象的模拟并将其发送到类对象。您可以像发送 to 的模拟对象一样执行此操作。EventEventMenuControllerEventServiceEventMenuController

将字段用作类的一部分而不是方法的一部分是更好的做法。这将使您可以灵活地模拟任何字段。

于 2013-10-17T08:33:57.900 回答