Question

I am learning Junit Mockito to test the spring- mvc controller using Spring 3.2 in Intellij. my controller is

 @RequestMapping(value = "/user", method = RequestMethod.GET)
    public String initUserSearchForm(ModelMap modelMap) {
        User user = new User();
        modelMap.addAttribute("User", user);
        return "linkedInUser";
    }

    @RequestMapping(value = "/byName", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    public
    @ResponseBody
    String getUserByName(HttpServletRequest request,@ModelAttribute("userClientObject") UserClient userClient) {
        String firstName = request.getParameter("firstName");
        String lastName = request.getParameter("lastName");
        return getUserByName(userClient, firstName, lastName);
    }

what i have done is i have one form to search the user by name. UserClient Object is a Session Attribute and i tried to write a junit test case for my controller

 @Test
    public void testInitUserSearchForm() throws Exception {
        this.liClient = client.createUserClient();
        mockMvc.perform(get("/user"))
                .andExpect(status().isOk())
                .andExpect(view().name("user"))
                .andExpect(forwardedUrl("/WEB-INF/pages/user.jsp"));
    }

    @Test
    public void testGeUserByName() throws Exception {
        String firstName = "Wills";
        String lastName = "Smith";         
        mockMvc.perform(get("/user-byName"))
                .andExpect(status().isOk());

    }

How do I test my getUserByName method and how would i add session attribute? Please anyone can help me to write testcase with possible tests for that method. Thanks in advance

Was it helpful?

Solution

hmmm.

You could try

mockMvc.perform(get("/user-byName").sessionAttr("userClientObject", userClientObject))
            .andExpect(status().isOk());

to setup userClientObject in test fixture.

What does "return getUserByName(userClient, firstName, lastName);" exactly do? If it doesn't involve external dependence, just assert your return in andExpect(jsonPath()) clause.

I thought it should be @SessionAttribute by the way.

OTHER TIPS

I use

mockMvc.perform(get("/user-byName").flashAttr("userClientObject", userClientObject)) .andExpect(status().isOk())

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top