【问题标题】:Controller Testing For SPRING-MVCSPRING-MVC 的控制器测试
【发布时间】:2013-08-07 06:13:57
【问题描述】:

当我不执行测试时,我的控制器出现错误提示空指针异常。一切正常。

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。帮我解决我的问题..谢谢

【问题讨论】:

  • 我已经设置好了。所有实体都有效。在控制器中没有值的简单测试工作正常。

标签: spring hibernate testing spring-mvc junit


【解决方案1】:

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

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

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

【讨论】:

  • 上下文加载正确。它适用于其他sontroller,我尝试了这个,但记录器输出没有变化。
  • 您有不同的测试环境?显示错误信息
  • FrameworkServlet '':初始化在 1 毫秒内完成 信息:co.softwarehouse.olt.web.controller.StudentInSectionController - 部分 ID 为:1 测试运行:1,失败:0,错误:1,跳过:0,经过的时间:0.223 秒
  • 你错过了错误中有趣的一点......用更多的堆栈跟踪更新你的问题。你是如何为测试设置 cotnext 的?
  • 一个 Xml 文件在 contextConfiguration 中。一切正常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-11
  • 2021-04-01
  • 2013-04-18
  • 2016-02-08
  • 1970-01-01
  • 2018-04-27
  • 2014-09-08
相关资源
最近更新 更多