nag*_*dra 10 java junit spring spring-mvc
我有一个控制器方法,我必须写一个junit测试
@RequestMapping(value = "/new", method = RequestMethod.GET)
public ModelAndView getNewView(Model model) {
EmployeeForm form = new EmployeeForm()
Client client = (Client) model.asMap().get("currentClient");
form.setClientId(client.getId());
model.addAttribute("employeeForm", form);
return new ModelAndView(CREATE_VIEW, model.asMap());
}
Run Code Online (Sandbox Code Playgroud)
使用spring mockMVC进行Junit测试
@Test
public void getNewView() throws Exception {
this.mockMvc.perform(get("/new")).andExpect(status().isOk()).andExpect(model().attributeExists("employeeForm")
.andExpect(view().name("/new"));
}
Run Code Online (Sandbox Code Playgroud)
我得到NullPointerException作为model.asMap().get("currentClient"); 在运行测试时返回null,如何使用spring mockmvc框架设置该值
响应以字符串链的形式给出(我猜是 json 格式,因为它是通常的休息服务响应),因此您可以通过以下方式通过结果响应访问响应字符串:
ResultActions result = mockMvc.perform(get("/new"));
MvcResult mvcResult = result.andExpect(status().isOk()).andReturn();
String jsonResponse = mvcResult.getResponse().getContentAsString();
Run Code Online (Sandbox Code Playgroud)
然后您可以通过 getResponse().getContentAsString() 访问响应。如果是json/xml,则再次将其解析为对象并检查结果。下面的代码只是确保 json 包含字符串链“employeeForm”(使用asertJ - 我推荐)
assertThat(mvcResult.getResponse().getContentAsString()).contains("employeeForm")
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你...