(拿来主义-9) Spring Boot构建RESTful API与单元测试(四)

  • @Controller:修饰class,用来创建处理http请求的对象
  • @RestController:Spring4之后加入的注解,原来在@Controller中返回json需要@ResponseBody来配合,如果直接用@RestController替代@Controller就不需要再配置@ResponseBody,默认返回json格式。
  • @RequestMapping:配置url映射

下面我们尝试使用Spring MVC来实现一组对User对象操作的RESTful API,配合注释详细说明在Spring MVC中如何映射HTTP请求、如何传参、如何编写单元测试。

RESTful API具体设计如下:

User实体定义:

public class User { 
 
    private Long id; 
    private String name; 
    private Integer age; 
 
    // 省略setter和getter 
     
}


实现对User对象的操作接口

 1 @RestController 
 2 @RequestMapping(value="/users")     // 通过这里配置使下面的映射都在/users下 
 3 public class UserController { 
 4  
 5     // 创建线程安全的Map 
 6     static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>()); 
 7  
 8     @RequestMapping(value="/", method=RequestMethod.GET) 
 9     public List<User> getUserList() { 
10         // 处理"/users/"的GET请求,用来获取用户列表 
11         // 还可以通过@RequestParam从页面中传递参数来进行查询条件或者翻页信息的传递 
12         List<User> r = new ArrayList<User>(users.values()); 
13         return r; 
14     } 
15  
16     @RequestMapping(value="/", method=RequestMethod.POST) 
17     public String postUser(@ModelAttribute User user) { 
18         // 处理"/users/"的POST请求,用来创建User 
19         // 除了@ModelAttribute绑定参数之外,还可以通过@RequestParam从页面中传递参数 
20         users.put(user.getId(), user); 
21         return "success"; 
22     } 
23  
24     @RequestMapping(value="/{id}", method=RequestMethod.GET) 
25     public User getUser(@PathVariable Long id) { 
26         // 处理"/users/{id}"的GET请求,用来获取url中id值的User信息 
27         // url中的id可通过@PathVariable绑定到函数的参数中 
28         return users.get(id); 
29     } 
30  
31     @RequestMapping(value="/{id}", method=RequestMethod.PUT) 
32     public String putUser(@PathVariable Long id, @ModelAttribute User user) { 
33         // 处理"/users/{id}"的PUT请求,用来更新User信息 
34         User u = users.get(id); 
35         u.setName(user.getName()); 
36         u.setAge(user.getAge()); 
37         users.put(id, u); 
38         return "success"; 
39     } 
40  
41     @RequestMapping(value="/{id}", method=RequestMethod.DELETE) 
42     public String deleteUser(@PathVariable Long id) { 
43         // 处理"/users/{id}"的DELETE请求,用来删除User 
44         users.remove(id); 
45         return "success"; 
46     } 
47  
48 }

下面针对该Controller编写测试用例验证正确性,具体如下。当然也可以通过浏览器插件等进行请求提交验证。

 1  2 
 3 import org.junit.Before;
 4 import org.junit.Test;
 5 import org.junit.runner.RunWith;
 6 import org.springframework.boot.test.context.SpringBootTest;
 7 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 8 import org.springframework.test.context.web.WebAppConfiguration;
 9 import org.springframework.test.web.servlet.MockMvc;
10 import org.springframework.test.web.servlet.RequestBuilder;
11 import org.springframework.test.web.servlet.setup.MockMvcBuilders;
12 
13 import static org.hamcrest.Matchers.equalTo;
14 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
15 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
16 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
17 
18 @RunWith(SpringJUnit4ClassRunner.class)
19 @SpringBootTest
20 @WebAppConfiguration
21 public class ApplicationTest {
22 
23     private MockMvc mvc;
24 
25     @Before
26     public void setUp() throws Exception {
27         mvc = MockMvcBuilders.standaloneSetup(new UserController()).build();
28     }
29 
30     @Test
31     public void testUserController() throws Exception {
32         // 测试UserController 
33         RequestBuilder request = null;
34 
35         // 1、get查一下user列表,应该为空 
36         request = get("/users/");
37         mvc.perform(request)
38                 .andExpect(status().isOk())
39                 .andExpect(content().string(equalTo("[]")));
40 
41         // 2、post提交一个user 
42         request = post("/users/")
43                 .param("id", "1")
44                 .param("name", "测试大师")
45                 .param("age", "20");
46         mvc.perform(request)
47                 .andExpect(content().string(equalTo("success")));
48 
49         // 3、get获取user列表,应该有刚才插入的数据 
50         request = get("/users/");
51         mvc.perform(request)
52                 .andExpect(status().isOk())
53                 .andExpect(content().string(equalTo("[{\"id\":1,\"name\":\"测试大师\",\"age\":20}]")));
54 
55         // 4、put修改id为1的user 
56         request = put("/users/1")
57                 .param("name", "测试终极大师")
58                 .param("age", "30");
59         mvc.perform(request)
60                 .andExpect(content().string(equalTo("success")));
61 
62         // 5、get一个id为1的user 
63         request = get("/users/1");
64         mvc.perform(request)
65                 .andExpect(content().string(equalTo("{\"id\":1,\"name\":\"测试终极大师\",\"age\":30}")));
66 
67         // 6、del删除id为1的user 
68         request = delete("/users/1");
69         mvc.perform(request)
70                 .andExpect(content().string(equalTo("success")));
71 
72         // 7、get查一下user列表,应该为空 
73         request = get("/users/");
74         mvc.perform(request)
75                 .andExpect(status().isOk())
76                 .andExpect(content().string(equalTo("[]")));
77 
78     }
79 
80 }


至此,我们通过引入web模块(没有做其他的任何配置),就可以轻松利用Spring MVC的功能,以非常简洁的代码完成了对User对象的RESTful API的创建以及单元测试的编写。其中同时介绍了Spring MVC中最为常用的几个核心注解:@Controller,@RestController,RequestMapping以及一些参数绑定的注解:@PathVariable,@ModelAttribute,@RequestParam等。

猜你喜欢

转载自www.cnblogs.com/dhl-2013/p/9385289.html