Spring Boot构建RESTful API与单元测试
如果您对Spring MVC不熟悉并且还没有尝试过快速入门案例,建议先看一下相关的内容。
@Controller:修饰class,用来创建处理http请求的对象@RestController:Spring4之后加入的注解,原来在@Controller中返回json需要@ResponseBody来配合,如果直接用@RestController替代@Controller就不需要再配置@ResponseBody,默认返回json格式。@RequestMapping:配置url映射
下面我们尝试使用Spring MVC来实现一组对User对象操作的RESTful API,配合注释详细说明在Spring MVC中如何映射HTTP请求、如何传参、如何编写单元测试。
RESTful API具体设计如下:
| 请求类型 | URL | 功能说明 |
|---|---|---|
| GET | /users | 查询用户列表 |
| POST | /users | 创建一个用户 |
| GET | /users/id | 根据id查询一个用户 |
| PUT | /users/id | 根据id更新一个用户 |
| DELETE | /users/id | 根据id删除一个用户 |
User实体定义:
public class User {
private Long id;
private String name;
private Integer age;
// 省略setter和getter
}
实现对User对象的操作接口
@RestController
@RequestMapping(value="/users") // 通过这里配置使下面的映射都在/users下
public class UserController {
// 创建线程安全的Map static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>());
@RequestMapping(value="/", method=RequestMethod.GET)
public List<User> getUserList() {
// 处理"/users/"的GET请求,用来获取用户列表 // 还可以通过@RequestParam从页面中传递参数来进行查询条件或者翻页信息的传递
List<User> r = new ArrayList<User>(users.values());
return r;
}
@RequestMapping(value="/", method=RequestMethod.POST)
public String postUser(@ModelAttribute User user) {
// 处理"/users/"的POST请求,用来创建User // 除了@ModelAttribute绑定参数之外,还可以通过@RequestParam从页面中传递参数
users.put(user.getId(), user);
return "success";
}
@RequestMapping(value="/{id}", method=RequestMethod.GET)
public User getUser(@PathVariable Long id) {
// 处理"/users/{id}"的GET请求,用来获取url中id值的User信息 // url中的id可通过@PathVariable绑定到函数的参数中 return users.get(id);
}
@RequestMapping(value="/{id}", method=RequestMethod.PUT)
public String putUser(@PathVariable Long id, @ModelAttribute User user) {
// 处理"/users/{id}"的PUT请求,用来更新User信息
User u = users.get(id);
u.setName(user.getName());
u.setAge(user.getAge());
users.put(id, u);
return "success";
}
@RequestMapping(value="/{id}", method=RequestMethod.DELETE)
public String deleteUser(@PathVariable Long id) {
// 处理"/users/{id}"的DELETE请求,用来删除User
users.remove(id);
return "success";
}
}
下面针对该Controller编写测试用例验证正确性,具体如下。当然也可以通过浏览器插件等进行请求提交验证。
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MockServletContext.class)
@WebAppConfigurationpublic class ApplicationTests {
private MockMvc mvc;
@Beforepublic void setUp() throws Exception {
mvc = MockMvcBuilders.standaloneSetup(new UserController()).build();
}
@Testpublic void testUserController() throws Exception {
// 测试UserController
RequestBuilder request = null;
// 1、get查一下user列表,应该为空
request = get("/users/");
mvc.perform(request)
.andExpect(status().isOk())
.andExpect(content().string(equalTo("[]")));
// 2、post提交一个user
request = post("/users/")
.param("id", "1")
.param("name", "测试大师")
.param("age", "20");
mvc.perform(request)
.andExpect(content().string(equalTo("success")));
// 3、get获取user列表,应该有刚才插入的数据
request = get("/users/");
mvc.perform(request)
.andExpect(status().isOk())
.andExpect(content().string(equalTo("[{\"id\":1,\"name\":\"测试大师\",\"age\":20}]")));
// 4、put修改id为1的user
request = put("/users/1")
.param("name", "测试终极大师")
.param("age", "30");
mvc.perform(request)
.andExpect(content().string(equalTo("success")));
// 5、get一个id为1的user
request = get("/users/1");
mvc.perform(request)
.andExpect(content().string(equalTo("{\"id\":1,\"name\":\"测试终极大师\",\"age\":30}")));
// 6、del删除id为1的user
request = delete("/users/1");
mvc.perform(request)
.andExpect(content().string(equalTo("success")));
// 7、get查一下user列表,应该为空
request = get("/users/");
mvc.perform(request)
.andExpect(status().isOk())
.andExpect(content().string(equalTo("[]")));
}
}
至此,我们通过引入web模块(没有做其他的任何配置),就可以轻松利用Spring MVC的功能,以非常简洁的代码完成了对User对象的RESTful API的创建以及单元测试的编写。其中同时介绍了Spring MVC中最为常用的几个核心注解:@Controller,@RestController,RequestMapping以及一些参数绑定的注解:@PathVariable,@ModelAttribute,@RequestParam等。
Spring Boot构建RESTful API与单元测试的更多相关文章
- 使用 Spring Boot 构建 RESTful API
1. 使用 Idea 创建 Spring Initializer 项目 在创建项目的对话框中添加 Web 和 Lombok,或者建立项目后在 pom.xml 中添加依赖: <dependency ...
- Spring Boot构建RESTful API
@Controller:修饰class,用来创建处理http请求的对象 @RestController:Spring4之后加入的注解,原来在@Controller中返回json需要@ResponseB ...
- SpringBoot 构建RestFul API 含单元测试
相关博文: 从消费者角度评估RestFul的意义 SpringBoot 构建RestFul API 含单元测试 首先,回顾并详细说明一下在快速入门中使用的 @Controller . @RestC ...
- Spring Boot构建 RESTful 风格应用
Spring Boot构建 RESTful 风格应用 1.Spring Boot构建 RESTful 风格应用 1.1 实战 1.1.1 创建工程 1.1.2 构建实体类 1.1.4 查询定制 1.1 ...
- Spring Boot2 系列教程(三十一)Spring Boot 构建 RESTful 风格应用
RESTful ,到现在相信已经没人不知道这个东西了吧!关于 RESTful 的概念,我这里就不做过多介绍了,传统的 Struts 对 RESTful 支持不够友好 ,但是 SpringMVC 对于 ...
- Spring Boot 2.x基础教程:构建RESTful API与单元测试
首先,回顾并详细说明一下在快速入门中使用的@Controller.@RestController.@RequestMapping注解.如果您对Spring MVC不熟悉并且还没有尝试过快速入门案例,建 ...
- 基于Spring Boot的RESTful API实践(一)
1. RESTful简述 REST是一种设计风格,是一组约束条件及原则,而遵循REST风格的架构就称为RESTful架构,资源是RESTful的核心,一个好的RESTful架构,通过URL就能很 ...
- Spring Boot中Restful Api的异常统一处理
我们在用Spring Boot去向前端提供Restful Api接口时,经常会遇到接口处理异常的情况,产生异常的可能原因是参数错误,空指针异常,SQL执行错误等等. 当发生这些异常时,Spring B ...
- spring boot构建restful服务
使用spring boot快速构建出restful服务 JPA实现REST 创建spring boot项目,在项目文件pom.xml中添加以下依赖: <dependency> <gr ...
随机推荐
- lodash接触:string-capitalize
1.capitalize : _.capitalize([string='']) Capitalizes the first character of string. 参数 [string=''] ( ...
- scanf与scanf_s的区别
scanf()函数是标准C中提供的标准输入函数,用以用户输入数据 scanf_s()函数是Microsoft公司VS开发工具提供的一个功能相同的安全标准输入函数,从vc++2005开始,VS系统提供了 ...
- 并发编程 17—— Lock
Java并发编程实践 目录 并发编程 01—— ThreadLocal 并发编程 02—— ConcurrentHashMap 并发编程 03—— 阻塞队列和生产者-消费者模式 并发编程 04—— 闭 ...
- H5页面左图右边文字如何布局
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8&qu ...
- php数据库封装与引用方法
1.做封装类 <?php class DBDA { //成员变量 数据库的四个条件 public $host="localhost"; public $uid = " ...
- 【仿真】【modelsim】:verilog功能仿真流程
一.编写verilog源文件,在diamond中编译.编写testbench文件.在diamond设置中将仿真工具设置为modelsim,运行仿真向导 二.自动进入modelsim, 编译全部 运行仿 ...
- Codeforces Round #380 (Div. 2) 解题报告
第一次全程参加的CF比赛(虽然过了D题之后就开始干别的去了),人生第一次codeforces上分--(或许之前的比赛如果都参加全程也不会那么惨吧),终于回到了specialist的行列,感动~.虽然最 ...
- iOS流量监控
http://code4app.com/snippets/one/iOS%E6%B5%81%E9%87%8F%E7%9B%91%E6%8E%A7/5020ba7a6803fae325000000 1. ...
- 手机抓包-fiddler
如果app走的是http协议,不用root,只需要通过fiddler做代理,就可以抓到所有请求. 1. fiddler+手机wifi设置 安装fiddler,勾中 Fiddler Options -& ...
- adb push和pull使用
1.运行cmd> 进入adb.exe目录 2.>adb connect ip 3.>adb remount 4.>adb push 本地apk全路径 /system/app/ ...