我正在学习Junit Mockito在Intellij中使用spring 3.2测试spring-mvc控制器。我的控制器是
@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);
}
我所做的是我有一个表单来按名称搜索用户。UserClient对象是会话属性,我尝试过为我的控制器写一个junit测试用例
@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());
}
如何测试我的getUserByName
方法以及如何添加会话属性?请任何人帮我编写带有该方法可能测试的测试用例。提前感谢
hmmm。
你可以试试
mockMvc.perform(get("/user-byName").sessionAttr("userClientObject", userClientObject))
.andExpect(status().isOk());
在测试夹具中设置userClientObject。
"return getUserByName(userClient,firstName,lastName);"究竟做了什么?如果它不涉及外部依赖,只需在andExpect(jsonPath())子句中断言您的return即可。
顺便说一下,我觉得应该是@SessionAttribute。
我使用
mockMvc.perform(get("/user-byName").flashAttr("userClientObject", userClientObject)) .andExpect(status().isOk())