在使用spring mvc编写接口服务时进行单元测试是颇有必要的,能够减小接口的出错率减小协同调试时间,尤为是对于先后端分离的web应用,这种应用先后端分工明确。对于spring项目要是进行单元测试,只需集成spring-test便可,最好导入servlet api,不然可能出现相似错误java
Caused by: java.util.MissingResourceException: Can't find bundle for base name javax.servlet.LocalStrings, locale zh_Cn
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency>
1.controller代码web
@Controller @RequestMapping("user") public class UserController{ @Resource private UserService userService; @ResponseBody @RequestMapping(value="/add",method = RequestMethod.POST) public CommonResult save(User entity){ return userService.save(entity); } @ResponseBody @RequestMapping(value="/update",method = RequestMethod.POST) public CommonResult update(User entity){ return userService.update(entity); } @ResponseBody @RequestMapping(value="/delete/{id}",method = RequestMethod.GET) public CommonResult delete(@PathVariable int id){ return userService.delete(id); } @ResponseBody @RequestMapping(value="/query/{id}",method = RequestMethod.GET) public CommonResult queryById(@PathVariable int id){ return userService.queryById(id); } /** * 使用@RequestBody接收json数据 */ @ResponseBody @RequestMapping(value = "jsonContent",method = RequestMethod.POST) public CommonResult testJsonContent(@RequestBody User user){ System.out.println("user:"+JSON.toJSONString(user)); return new CommonResult(); } }
2.测试代码:spring
//静态导入 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.web.context.WebApplicationContext; /** * controller restful接口单元测试 * * @author yu * @date 2016-12-30 21:24:57 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({ "classpath:spring-mybatis.xml", "classpath:spring-mvc.xml" }) public class UserControllerTest extends ControllerBaseTest { @Resource private WebApplicationContext wac; private MockMvc mockMvc; @Before public void setup() { this.mockMvc = webAppContextSetup(this.wac).build(); } /** * 测试controller add接口 * * @throws Exception */ @Test public void testAdd() throws Exception { MvcResult result = mockMvc.perform(post("/user/add") .contentType(MediaType.APPLICATION_JSON) .param("id", "1") .param("name", "zhangsan") ).andExpect(status().isOk()).andDo(print()).andReturn(); System.out.println("result:" + result.getResponse().getContentAsString()); } /** * 测试controller queryById接口 * * @throws Exception */ @Test public void testQueryById() throws Exception { MvcResult result = mockMvc.perform(get("/user/query/{id}", 1) .contentType(MediaType.APPLICATION_JSON) .param("param1", "pm1") ).andExpect(status().isOk()).andDo(print()).andReturn(); System.out.println("result:" + result.getResponse().getContentAsString()); } /** * 测试controller update接口 * * @throws Exception */ @Test public void testUpdate() throws Exception { MvcResult result = mockMvc.perform(get("/user/update") .contentType(MediaType.APPLICATION_JSON) .param("id", "1") .param("name", "list") ).andExpect(status().isOk()).andDo(print()).andReturn(); System.out.println("result:" + result.getResponse().getContentAsString()); } /** * 测试controller delete接口 * * @throws Exception */ @Test public void testDelete() throws Exception { MvcResult result = mockMvc.perform(get("/user/delete/{id}", 1) .contentType(MediaType.APPLICATION_JSON) .param("param1", "pm1") ).andExpect(status().isOk()).andDo(print()).andReturn(); System.out.println("result:" + result.getResponse().getContentAsString()); } /** * 测试发送content * @throws Exception */ @Test public void testSendJsonContent() throws Exception { User user = new User(); user.setId(1); user.setName("lisi"); String userJson = JSON.toJSONString(user);//发送json MvcResult result = mockMvc.perform(post("/user/jsonContent") .contentType(MediaType.APPLICATION_JSON) .content(userJson) ).andExpect(status().isOk()).andDo(print()).andReturn(); System.out.println("result:" + result.getResponse().getContentAsString()); } }
测试时加sessionjson
HashMap<String, Object> sessionattr = new HashMap<String, Object>(); sessionattr.put("username", "xyyy"); MvcResult result = mockMvc.perform(post("/news/add") // .sessionAttrs(sessionattr) .contentType(MediaType.APPLICATION_JSON)
注意:若是是测试类中只加载spring的配置,不加载spring mvc配置会致使@ResponseBody返回的值不能转换成json(因此其实就是spring mvc配置文件中定义了数据装换)而出现http status 406错误后端
@ContextConfiguration({"classpath:spring-mybatis.xml"})
这种状况对于@RestController仍然能够得到数据,可是须要从MvcResult中调用api
getModelAndView().getModel()
获得数据。spring-mvc