SPRING-MVC的控制器测试

时间:2013-08-07 06:13:57

标签: spring hibernate testing spring-mvc junit

我在控制器中遇到错误说空指针异常,而我没有执行测试。一切正常。

Controller :
@RequestMapping(value = "/studentinsection/{sectionId}", method = RequestMethod.GET)
    public ModelAndView studentInSectionForm(@ModelAttribute("studentInSectionFormData") StudentInSectionForm studentInSectionFormData,
                                             @PathVariable Integer sectionId,
                                             ModelMap model) {
        ArrayList<StudentInSections> studentInSectionList = (ArrayList<StudentInSections>)
                studentInSectionsService.retrieveAllStudentInSections(sectionId, 1);

        StudentSection studentSection = studentSectionService.retrieveStudentSection(sectionId);

        logger.info("section Name is:" + studentSection.getSectionName());

        ArrayList<User> userList = new ArrayList<User>();
        for (StudentInSections studentInSections : studentInSectionList) {
            String studentName =
                    (userService.retrieveUserName(studentInSections.getStudentId(), 1));
            User users = userService.retrieveUser(studentName);
            userList.add(users);
        }


        logger.info("sectionId is " + sectionId);

        ArrayList<User> allStudents = (ArrayList<User>)
                userService.retrieveAllStudents();

        studentInSectionFormData.setStudentInSectionList(studentInSectionList);
        model.addAttribute("studentList", allStudents);
        model.addAttribute("userList", userList);
        model.addAttribute("studentSectionName", studentSection.getSectionName());
        model.addAttribute("studentSectionId", studentSection.getSectionId());
        return new ModelAndView("studentinsection", "studentInSectionFormData", studentInSectionFormData);
    }


Testing is as follow:

    @Test
    public void testStudentInSectionForm() throws Exception {
        mockMvc.perform(get("/studentinsection/1"))
                .andExpect(status().isFound())
                .andExpect(redirectedUrl("studentinsection"));
    }

这会将所有内容传递给控制器​​,即使sectionId在logger中打印1也比studentin sectionList返回nullMointerException。帮我解决我的问题.. Thanx

1 个答案:

答案 0 :(得分:0)

看起来上下文没有正确加载。什么是异常堆栈跟踪。

如果您这样做,也可以查看请求:

  mockMvc.perform(get("/studentinsection/1"))
   .andExpect(status().isFound())
   .andDo(print())