簡體   English   中英

SPRING-MVC的控制器測試

[英]Controller Testing For 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還要好。 幫助我解決我的問題。

看來上下文未正確加載。 什么是異常stacktrace。

您也可以查看請求:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM