如何在测试中使用MockMvc避免NullPointerException?

时间:2013-10-17 08:21:16

标签: java testing spring-mvc mocking spring-mvc-test

我有控制器:

@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将事件传递给服务器端(控制器方法)?

1 个答案:

答案 0 :(得分:0)

Event类对象未初始化。您可以根据测试用例创建Event对象或创建Event对象的模拟,并将其发送到EventMenuController类对象。您可以执行此操作,类似于将EventService的模拟对象发送到EventMenuController的方式。

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