Swagger测试Restful API
原创
©著作权归作者所有:来自51CTO博客作者全栈测试笔记的原创作品,请联系作者获取转载授权,否则将追究法律责任
swagger出现背景
我们构建Restful API的目的通常都是由于多终端的原因,这些终端会共用很多底层业务逻辑,因此我们会抽象出这样一层来同时服务于多个移动端或者Web前端,不同端由不同的团队或者小组负责,为了减少与其他团队平时开发期间的频繁沟通成本,传统做法我们会创建一份Restful API文档来记录所有接口细节,但是,由于接口多且复杂,这样的做法是很难执行的,且效果差。
而Swagger2可以轻松的整合到Spring Boot中,既可以减少我们创建文档的工作量,同时说明内容又整合入实现代码中,让维护文档和修改代码整合为一体,可以让我们在修改代码逻辑的同时方便的修改文档说明。另外Swagger2也提供了强大的页面测试功能来调试每个RESTful API。
Spring Boot集成swagger
待补充
修改Controller层
package com.qzcsbj.demo.controller;
import com.qzcsbj.demo.commons.ResultCode;
import com.qzcsbj.demo.commons.ResultCommon;
import com.qzcsbj.demo.mapper.UserMapper;
import com.qzcsbj.demo.pojo.User;
import com.qzcsbj.demo.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* @公众号 : 全栈测试笔记
* @描述 : <>
*/
@Api(tags = {"用户操作"})
@RestController
@RequestMapping("/v2")
public class UserController {
@Autowired
UserService userService;
// restful api:增
@ApiOperation(value = "添加用户", notes = "添加一个用户")
@PostMapping("/users")
public ResultCommon add(User user){
int n = userService.add(user);
if (n>0){
return ResultCommon.success(ResultCode.SUCCESS);
} else {
return ResultCommon.fail(ResultCode.FAIL);
}
}
// restful api:删
@ApiOperation(value = "根据id删除用户", notes = "根据id删除一个用户")
@DeleteMapping("/users/{id}")
public ResultCommon delete(@PathVariable("id") Integer id){
int n = userService.delete(id);
if (n>0){
return ResultCommon.success(ResultCode.SUCCESS);
} else {
return ResultCommon.fail(ResultCode.FAIL);
}
}
// restful api:改
@ApiOperation(value = "修改用户", notes = "根修改用户信息")
@PutMapping("/users")
public ResultCommon update(User user){
int n = userService.update(user);
if (n>0){
return ResultCommon.success(ResultCode.SUCCESS);
} else {
return ResultCommon.fail(ResultCode.FAIL);
}
}
// restful api:查
@ApiOperation(value = "根据id获取用户", notes = "根据id获取用户信息")
@GetMapping("/users/{id}")
// @RequestMapping(value = "/user/{id}", method=RequestMethod.GET)
public ResultCommon findById(@PathVariable("id") Integer id){
User user = userService.findById(id);
return ResultCommon.success(ResultCode.SUCCESS, user);
}
// restful api:查所有
@ApiOperation(value = "获取用户列表", notes = "获取所有用户")
@GetMapping("/users")
public ResultCommon findAll(){
List<User> users = userService.findAll();
return ResultCommon.success(ResultCode.SUCCESS, users);
}
}
效果
访问:http://localhost:8082/swagger-ui.html,端口根据实际情况修改即可。

swagger上进行测试
这样就可以不用postman或者jmeter测试了
没有前端,可以通swagger模拟前端进行测试
增
id是自增的不用填,addtime是通过函数获取的也不用填


数据库中新增成功

删


数据库中删除成功

改
修改前



修改后

查


查所有


__EOF__
本文作者:持之以恒(韧)