对于SPRING-MVC的控制器测试

问题描述:

我在我的控制器中出现错误说出空指针异常,而当我不执行测试时。一切正常。对于SPRING-MVC的控制器测试

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是越来越在记录仪印刷1比也Studentin我sectionList返回nullMointerException。帮我解决我的问题.. Thanx

+0

我已一切正常。所有实体都有效。控制器中没有值的简单测试工作正常。 –

它看起来像上下文未被正确加载。什么是异常堆栈跟踪。

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

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

上下文正确加载。它适用于其他sontroller,我试过这个,但没有改变记录器的输出。 –

+0

您有不同的测试环境吗?显示错误信息 – NimChimpsky

+0

FrameworkServlet'':在1ms内完成初始化 信息:co.softwarehouse.olt.web.controller.StudentInSectionController - 节Id是:1 测试运行:1,失败:0,错误:1,跳过: 0,所用时间:0.223秒