这里总结出两种方式测试restful
① RestTemplate
② MockMvc
1、Users.class
package com.testRestful.model; import lombok.Data; /** * @author * @date 2018/6/25 */ @Data public class Users { private String id; private String userName; private String password; private String age; private String email; }
2.UserService.class
package com.testRestful.service; import com.testRestful.model.Users; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; @Service public class UserService { /** * 查询所有用户 * @return */ public List<Users> getAll() { List<Users> list = new ArrayList<>(); Users users = new Users(); users.setId("001"); users.setUserName("xxxxx"); users.setAge("20"); users.setEmail("1232@qq.com"); Users users1 = new Users(); users1.setId("002"); users1.setUserName("qqqq"); users1.setAge("18"); users1.setEmail("1232@qq.com"); list.add(users); list.add(users1); return list; } /** * 根据id查询用户 * @param id * @return */ public Users getUserById(String id) { Users users = new Users(); users.setId(id); users.setUserName("xxxxx"); users.setAge("20"); users.setEmail("1232@qq.com"); return users; } /** * 根据id删除用户 * @param id * @return */ public Users deleteUserById(String id) { //执行删除操作 Users users = new Users(); users.setId(id); users.setUserName("该用户是删除的用户"); users.setAge("20"); users.setEmail("1232@qq.com"); return users; } /** * 根据id修改用户 * @param id * @return */ public Users editUserById(String id) { //执行修改操作 Users users = new Users(); users.setId(id); users.setUserName("该用户是修改的用户"); users.setAge("20"); users.setEmail("1232@qq.com"); return users; } /** * 保存用户 * @param users * @return */ public Users save(Users users) { //执行保存操作 return users; } }
3. UserController.class
package com.testRestful.controller; import com.testRestful.model.Users; import com.testRestful.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController public class UserController { @Autowired private UserService userService; /** * 查询所有用户 * @return */ @RequestMapping(value = "users",method = RequestMethod.GET) public List<Users> getAll() { List<Users> users = userService.getAll(); return users; } /** * 根据id查询用户通过占位符GET方式(restTemplate使用的方法) * @param id * @return */ @RequestMapping(value = "users/{id}",method = RequestMethod.GET) public Users getUserById(@PathVariable(name = "id") String id) { return userService.getUserById(id); } /** * 根据id查询用户通过占位符GET方式(mockMvc使用的方法) * @param id * @return */ @RequestMapping(value = "getusers",method = RequestMethod.GET) public Users getUsers(String id) { return userService.getUserById(id); } /** * 根据id删除用户 * @param id * @return */ @RequestMapping(value = "users/{id}",method = RequestMethod.DELETE) public Users deleteUserById(@PathVariable(name = "id") String id) { System.out.println("请求的参数为:" + id); return userService.deleteUserById(id); } /** * 根据id修改用户 * @param id * @return */ @RequestMapping(value = "users/{id}",method = RequestMethod.PUT) public Users editUserById(@PathVariable(name = "id") String id) { System.out.println("请求的参数为:" + id); return userService.editUserById(id); } /** * 保存用户(restTemplate使用的方法) * @param users * @return */ @RequestMapping(value = "save",method = RequestMethod.POST) public Users save(@RequestBody Users users) { return userService.save(users); } /** * 保存用户(mockMvc使用的方法) * @param users * @return */ @RequestMapping(value = "saveAdd",method = RequestMethod.POST) public Users saveAdd(Users users) { return userService.save(users); } /** * 根据id查询用户通过传参POST方式 * @param id * @return */ @RequestMapping(value = "getUserByIdRePost",method = RequestMethod.POST) public Users getUserByIdRePost(@RequestBody String id) { return userService.getUserById(id); } }
4.RestTemplate测试方法
总结RestTemplate
①GET getForEntity和getForObject只能通过url占位符进行传参
②DELETE delete
③PUT put
④POST postForEntity和postForObject可以进行传参但是controller参数要通过@RequestBody注解才能获取
Users getUserByIdRePost(@RequestBody String id)
Users save(@RequestBody Users users)
package com.testRestful.test; import com.testRestful.model.Users; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.web.client.RestTemplate; import java.util.HashMap; import java.util.List; /** * @author luoxianwei * @date 2018/6/22 * * 总结RestTemplate * ①GET getForEntity和getForObject只能通过url占位符进行传参 * ②DELETE delete * ③PUT put * ④POST postForEntity和postForObject可以进行传参但是controller参数要通过@RequestBody注解才能获取 * Users getUserByIdRePost(@RequestBody String id) * Users save(@RequestBody Users users) */ @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest public class TestRestTemplate { public static final RestTemplate restTemplate = new RestTemplate(); /** * 查询所有用户 */ @Test public void getAll() { ResponseEntity<List> responseEntity = restTemplate.getForEntity("http://localhost:8083/users", List.class); List list = responseEntity.getBody(); System.out.println("getForEntity请求回来的值是:" + list.toString()); List lists = restTemplate.getForObject("http://localhost:8083/users", List.class); System.out.println("getForObject请求回来的值是:" + lists.toString()); } /** * ①根据id查询用户通过占位符GET方式 */ @Test public void getUserById() { ResponseEntity<Users> responseEntity = restTemplate.getForEntity("http://localhost:8083/users/22222222222", Users.class); System.out.println("getForEntity请求回来的对象是:" + responseEntity.getBody()); Users user = restTemplate.getForObject("http://localhost:8083/users/001", Users.class); System.out.println("getForObject请求回来的对象是:" + user); } /** * ②根据id查询用户通过传参 * 1.getForEntity(String url,Class responseType,Object...urlVariables): * 该方法提供了三个参数,其中url为请求的地址,responseType为请求响应体body的包装类型,urlVariables为url中的参数绑定。 * GET请求的参数绑定通常使用url中拼接的方式,比如http://USER-SERVICE/user?name=did我们可以像这样自已将参数拼接到url中, * 但更好的方法是在url中使用占位符并配合urlVariables参数实现GET请求的参数绑定, * 比如url定义为htip://USER-SERVICE/user?name={1},然后可以这样来调用: * getForEntity("http://USER-SERVICE/user?name={1}",String.class,"didi")'其中第三个参数didi会替换url中的{1}占位符。 * <p> * 这里需要注意的是,由于urlVariables参数是一个数组,所以它的顺序会对应url中占位符定义的数字顺序。 */ @Test public void getUserById2() { String id = "22222222222"; ResponseEntity<Users> responseEntity = restTemplate.getForEntity("http://localhost:8083/users/{id}", Users.class, id); ResponseEntity<Users> responseEntity1 = restTemplate.getForEntity("http://localhost:8083/users/{1}", Users.class, id); System.out.println("getForEntity请求回来的对象是①:" + responseEntity.getBody()); System.out.println("getForEntity请求回来的对象是②:" + responseEntity1.getBody()); Users user = restTemplate.getForObject("http://localhost:8083/users/{id}", Users.class, id); System.out.println("getForObject请求回来的对象是:" + user); } /** * ③根据id查询用户通过使用map封装参数 * 2.getForEntity(String url,Class responseType,Map urlVariables): * 该方法提供的参数中,只有urlVariables的参数类型与上面的方法不同。这里使用了Map类型,所以使用该方法进行参数绑定时需要在占位符中指定Map中参 * 数的key值,比如url定义为http://USER-SERVICE/user?name={name),在Map类型的urlVariables中,我们就需要put一个key为name的参数来绑 * 定url中{name}占位符的值,比如: */ @Test public void getUserByIdMap() { HashMap<String, String> map = new HashMap<>(); map.put("id", "666666666"); ResponseEntity<Users> responseEntity = restTemplate.getForEntity("http://localhost:8083/users/{id}", Users.class, map); System.out.println("getForEntity请求回来的对象是:" + responseEntity.getBody()); Users user = restTemplate.getForObject("http://localhost:8083/users/{id}", Users.class, map); System.out.println("getForObject请求回来的对象是:" + user); } /** * 根据id删除用户 */ @Test public void deleteUserById() { restTemplate.delete("http://localhost:8083/users/001"); System.out.println("delete方法没有返回值"); } /** * 根据id修改用户 */ @Test public void editUserById() { restTemplate.put("http://localhost:8083/users/003", String.class); System.out.println("put方法没有返回值"); } /** * 保存用户 */ @Test public void save() { Users users = new Users(); users.setId("888"); users.setUserName("xxxxx"); users.setAge("20"); users.setEmail("1232@qq.com"); ResponseEntity<Users> responseEntity = restTemplate.postForEntity("http://localhost:8083/save", users, Users.class); Users users1 = responseEntity.getBody(); System.out.println("postForEntity保存的对象为:" + users1); Users users2 = restTemplate.postForObject("http://localhost:8083/save", users, Users.class); System.out.println("postForObject保存的对象为:" + users2); } /** * 根据id查询用户通过传参POST方式 */ @Test public void getUserByIdRePost() { String id = "9999999"; ResponseEntity<Users> responseEntity = restTemplate.postForEntity("http://localhost:8083/getUserByIdRePost", id, Users.class); Users users1 = responseEntity.getBody(); System.out.println("postForEntity根据id查询用户通过传参获得对象为:" + users1); Users users2 = restTemplate.postForObject("http://localhost:8083/getUserByIdRePost", id, Users.class); System.out.println("postForObject根据id查询用户通过传参获得对象为:" + users2); } }
5.MockMvc测试方法
package com.testRestful.test; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @Configuration @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest public class TestRestMockMvc { @Autowired private WebApplicationContext wac; private MockMvc mockMvc; @Before public void setup() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); } /** * 测试获得一个对象① * * @throws Exception */ @Test public void testDetailUser() throws Exception { ResultActions resultActions = mockMvc.perform(get("/users/c240da50-013b-4b3d-8c46-77976e288497") .contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andDo(print()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)); MockHttpServletResponse response = resultActions.andReturn().getResponse(); String contentAsString = response.getContentAsString(); System.out.println("获取的对象为:" + contentAsString); } /** * 测试获得一个对象② * * @throws Exception */ @Test public void testDetailUser2() throws Exception { ResultActions resultActions = mockMvc.perform(get("/getusers").param("id","00232") .contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andDo(print()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)); MockHttpServletResponse response = resultActions.andReturn().getResponse(); String contentAsString = response.getContentAsString(); System.out.println("获取的对象为:" + contentAsString); } /** * 测试删除一个对象 * * @throws Exception */ @Test public void testDeleteUser() throws Exception { ResultActions resultActions = mockMvc.perform(delete("/users/c240da50-013b-4b3d-8c46-77976e288497") .contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andDo(print()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)); MockHttpServletResponse response = resultActions.andReturn().getResponse(); String contentAsString = response.getContentAsString(); System.out.println("删除一个对象为:" + contentAsString); } /** * 测试修改一个对象 * * @throws Exception */ @Test public void testPutUser() throws Exception { ResultActions resultActions = mockMvc.perform(put("/users/c240da50-013b-4b3d-8c46-77976e288497") .contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andDo(print()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)); MockHttpServletResponse response = resultActions.andReturn().getResponse(); String contentAsString = response.getContentAsString(); System.out.println("修改一个对象为:" + contentAsString); } /** * 测试添加一个对象 * * @throws Exception */ @Test public void testPostUser() throws Exception { ResultActions resultActions = mockMvc.perform(post("/saveAdd").param("userName", "test").param("age", "18") .contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andDo(print()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)); MockHttpServletResponse response = resultActions.andReturn().getResponse(); String contentAsString = response.getContentAsString(); System.out.println("添加一个对象为:" + contentAsString); } /** * 测试获得所有对象 * * @throws Exception */ @Test public void testGetAllUser() throws Exception { ResultActions resultActions = mockMvc.perform(get("/users") .contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andDo(print()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)); MockHttpServletResponse response = resultActions.andReturn().getResponse(); String contentAsString = response.getContentAsString(); System.out.println("获得所有对象为:" + contentAsString); } }