Reputation: 3373
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
Upvotes: 3
Views: 3064
Reputation: 377
I use
mockMvc.perform(get("/user-byName").flashAttr("userClientObject", userClientObject)) .andExpect(status().isOk())
Upvotes: 0
Reputation: 7283
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.
Upvotes: 1