swagger接口测试工具介绍及使用
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
- 前言
- 一、swagger是什么?
- 二、使用步骤
- 2.1.引入依赖
- 2.2.编写config配置文件
- 3.在需要测试的接口类上添加注解
- 3.1@Api
- 3.2@ApiOperation
- 3.3@ApiParam
- 3.4@ApiModel
- 3.5@ApiModelProperty
- 3.6@ApiImplicitParam
- 3.7@ApiImplicitParams
- 4.启用swagger测试
- 总结
前言
在web开发中需要对接口进行测试,这时就需要用到测试工具。一般使用较多的测试工具有swagger(丝袜哥)和postman(邮递员)。在这里来总结一下swagger的使用方法和步骤。
一、swagger是什么?
Swagger 官网地址:https://swagger.io/Swagger
有了丝袜哥,只需要在类或者接口等地方加上几个注解,然后在浏览器通过对应的url访问swagger的ui界面,这个界面上会展示接口的所有信息,点击对应的接口即可进行测试,非常方便,界面也做的非常赏心悦目。
二、使用步骤
2.1.引入依赖
<dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>2.7.0</version></dependency><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</artifactId><version>2.7.0</version></dependency>
2.2.编写config配置文件
代码如下(示例):
import com.google.common.base.Predicates;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;@Configuration
@EnableSwagger2
public class SwaggerConfig {@Beanpublic Docket webApiConfig() {return new Docket(DocumentationType.SWAGGER_2).groupName("webApi").apiInfo(webApiInfo()).select().paths(Predicates.not(PathSelectors.regex("/admin/.*"))).paths(Predicates.not(PathSelectors.regex("/error.*"))).build();}private ApiInfo webApiInfo(){return new ApiInfoBuilder().title("网站-课程中心API文档").description("本文档描述了课程中心微服务接口定义").version("1.0").contact(new Contact("Helen", "http://www.baidu.com","55317332@qq.com")).build();}
}
需要在SwaggerConfig类上加上@Configuration和@EnableSwagger2注解
3.在需要测试的接口类上添加注解
swagger常用注解有:
3.1@Api
修饰整个类,描述Controller的作用,示例:
@Api(tags="标签")
@Controller
public class TagsController {
……
}
其它属性:
value :url的路径值
tags :如果设置这个值、value的值会被覆盖
description :对api资源的描述
basePath: 基本路径
position :如果配置多个Api 想改变显示的顺序位置
produces :如, “application/json, application/xml”
consumes: 如, “application/json, application/xml”
protocols :协议类型,如: http, https, ws, wss.
authorizations :高级特性认证时配置
hidden :配置为true ,将在文档中隐藏
3.2@ApiOperation
描述一个类的一个方法,示例:
@ApiOperation:"用在请求的方法上,说明方法的作用"value="说明方法的作用"notes="方法的备注说明"
3.3@ApiParam
单个参数描述
3.4@ApiModel
用对象来接收参数
3.5@ApiModelProperty
用对象接收参数时,描述对象的一个字段
3.6@ApiImplicitParam
一个请求参数
3.7@ApiImplicitParams
多个请求参数
4.启用swagger测试
打开网址http://localhost:8080/swagger-ui.html(此处的端口号为项目配置的端口号),便可以进行测试。
点击需要测试的方法,填入正确的传递参数,然后点击try it out即可。
总结
swagger的使用很方便,在页面上展示出所有需要测试的接口,一目了然。
如果在使用时有报错,可以考虑是否为版本问题,考虑换新一点的swagger依赖或者降低springboot版本。
2.5.6的springboot与2.7.0的swagger组合可正常使用。