我们之前使用的@Controller@RestController@RequestMapping注解。如果您对Spring MVC不熟悉并且还没有尝试过快速入门案例,建议先看一下springMVC的注解;

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

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

RESTful API具体设计如下:

Spring Boot学习(三)之构建RESTful API与单元测试

User.java实体类 定义:

01 package com.xiaojingg.domain;
02 /**
03  * @author 筱进GG
04  */
05 public class User {
06  
07     private Long id;
08     private String name;
09     private Integer age;
10  
11     public Long getId() {
12         return id;
13     }
14  
15     public void setId(Long id) {
16         this.id = id;
17     }
18  
19     public String getName() {
20         return name;
21     }
22  
23     public void setName(String name) {
24         this.name = name;
25     }
26  
27     public Integer getAge() {
28         return age;
29     }
30  
31     public void setAge(Integer age) {
32         this.age = age;
33     }
34 }

实现对User对象的操作接口

01 package com.xiaojingg.web;
02  
03 import com.xiaojingg.domain.User;
04  
05 import java.util.*;
06  
07 import org.springframework.web.bind.annotation.*;
08 /**
09  * @author 筱进GG
10  */
11 @RestController
12 @RequestMapping(value="/users")     // 通过这里配置使下面的映射都在/users下,可去除
13 public class UserController {
14  
15     static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>());
16  
17     @RequestMapping(value="/", method=RequestMethod.GET)
18     public List<User> getUserList() {
19         // 处理"/users/"的GET请求,用来获取用户列表
20         // 还可以通过@RequestParam从页面中传递参数来进行查询条件或者翻页信息的传递
21         List<User> r = new ArrayList<User>(users.values());
22         return r;
23     }
24  
25     @RequestMapping(value="/", method=RequestMethod.POST)
26     public String postUser(@ModelAttribute User user) {
27         // 处理"/users/"的POST请求,用来创建User
28         // 除了@ModelAttribute绑定参数之外,还可以通过@RequestParam从页面中传递参数
29         users.put(user.getId(), user);
30         return "success";
31     }
32  
33     @RequestMapping(value="/{id}", method=RequestMethod.GET)
34     public User getUser(@PathVariable Long id) {
35         // 处理"/users/{id}"的GET请求,用来获取url中id值的User信息
36         // url中的id可通过@PathVariable绑定到函数的参数中
37         return users.get(id);
38     }
39  
40     @RequestMapping(value="/{id}", method=RequestMethod.PUT)
41     public String putUser(@PathVariable Long id, @ModelAttribute User user) {
42         // 处理"/users/{id}"的PUT请求,用来更新User信息
43         User u = users.get(id);
44         u.setName(user.getName());
45         u.setAge(user.getAge());
46         users.put(id, u);
47         return "success";
48     }
49  
50     @RequestMapping(value="/{id}", method=RequestMethod.DELETE)
51     public String deleteUser(@PathVariable Long id) {
52         // 处理"/users/{id}"的DELETE请求,用来删除User
53         users.remove(id);
54         return "success";
55     }
56  
57 }

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

 

01 package com.xiaojingg.test;
02  
03 import com.xiaojingg.web.HelloController;
04 import com.xiaojingg.web.UserController;
05 import org.junit.Before;
06 import org.junit.Test;
07 import org.junit.runner.RunWith;
08 import org.springframework.boot.test.SpringApplicationConfiguration;
09 import org.springframework.http.MediaType;
10 import org.springframework.mock.web.MockServletContext;
11 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
12 import org.springframework.test.context.web.WebAppConfiguration;
13 import org.springframework.test.web.servlet.MockMvc;
14 import org.springframework.test.web.servlet.RequestBuilder;
15 import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
16 import org.springframework.test.web.servlet.setup.MockMvcBuilders;
17  
18 import static org.hamcrest.Matchers.equalTo;
19 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
20 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
21 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
22  
23  
24 /**
25  * @author 筱进GG
26  */
27 @RunWith(SpringJUnit4ClassRunner.class)
28 @SpringApplicationConfiguration(classes = MockServletContext.class)
29 @WebAppConfiguration
30 public class ApplicationTests {
31  
32     private MockMvc mvc;
33  
34     @Before
35     public void setUp() throws Exception {
36         mvc = MockMvcBuilders.standaloneSetup(
37                 new HelloController(),
38                 new UserController()).build();
39     }
40  
41     @Test
42     public void getHello() throws Exception {
43         mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().string(equalTo("Hello World")));
44     }
45  
46     @Test
47     public void testUserController() throws Exception {
48 //      测试UserController
49         RequestBuilder request = null;
50  
51         // 1、get查一下user列表,应该为空
52         request = get("/users/");
53         mvc.perform(request).andExpect(status().isOk()) .andExpect(content().string(equalTo("[]")));
54  
55         // 2、post提交一个user
56         request = post("/users/")   .param("id""1").param("name""筱进GG").param("age""20");
57         mvc.perform(request)
58 //              .andDo(MockMvcResultHandlers.print())
59                 .andExpect(content().string(equalTo("success")));
60  
61         // 3、get获取user列表,应该有刚才插入的数据
62         request = get("/users/");
63         mvc.perform(request)
64                 .andExpect(status().isOk())
65                 .andExpect(content().string(equalTo("[{\"id\":1,\"name\":\"筱进GG\",\"age\":20}]")));
66  
67         // 4、put修改id为1的user
68         request = put("/users/1")
69                 .param("name""筱进GG测试")
70                 .param("age""30");
71         mvc.perform(request)
72                 .andExpect(content().string(equalTo("success")));
73  
74         // 5、get一个id为1的user
75         request = get("/users/1");
76         mvc.perform(request)
77                 .andExpect(content().string(equalTo("{\"id\":1,\"name\":\"筱进GG测试\",\"age\":30}")));
78  
79         // 6、del删除id为1的user
80         request = delete("/users/1");
81         mvc.perform(request)
82                 .andExpect(content().string(equalTo("success")));
83  
84         // 7、get查一下user列表,应该为空
85         request = get("/users/");
86         mvc.perform(request)
87                 .andExpect(status().isOk())
88                 .andExpect(content().string(equalTo("[]")));
89  
90     }
91  
92 }

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

注:springboot1.4之后Spring Boot取消了@SpringApplicationConfiguration这个注解,用@SpringBootTest就可以了

1 @RunWith(SpringJUnit4ClassRunner.class)
2 //@SpringApplicationConfiguration(classes = MockServletContext.class)
3 @SpringBootTest(classes = MockServletContext.class)
4 @WebAppConfiguration

小伙伴们可以试试;

欢迎大家一起交流学习SpringBoot,java等领域的技术,交流群 : 587674051 博客的源码也在里面


相关文章: