环境:Spring Boot,Swagger,gradle,Postman,newman,jenkins
SpringBoot环境搭建。
Swagger简介
Swagger 是一款RESTFUL接口的文档在线自动生成+功能测试功能软件。
一、SpringBoot集成Swagger
1.build.gradle增加swagger相关jar包,maven项目同理。
2.增加SwaggerConfig配置文件。
前两步完成,访问http://localhost:8080/demoService/swagger-ui.html#/
即可看见swagger的api页面了。下面几个步骤是为了解决一些配置问题,没有以下几种问题可以不用配置。
package com.example.demo;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
@Configuration
@EnableSwagger2
@ConditionalOnExpression("${swagger.enable:true}")
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
ParameterBuilder sessionIdPar = new ParameterBuilder();
List pars = new ArrayList();
sessionIdPar.name("SESSIONID").description("用户 sessionid")
.modelRef(new ModelRef("string")).parameterType("header")
.required(true).build();
pars.add(sessionIdPar.build()); //根据每个方法名也知道当前方法在设置什么参数
return new Docket(DocumentationType.SWAGGER_2)
.globalOperationParameters(pars)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("springboot利用swagger构建api文档")
.description("简单优雅的restfun风格")
.version("1.0")
.build();
}
}
3.生产环境不部署问题
解决生产环境不部署问题,application.yml增加配置信息。SwaggerConfig增加注解信息,完整配置文件信息在下方。
swagger.enable
4. 配置用户名密码
配置用户名密码访问swagger需要增加spring-boot-starter-security。
compile('org.springframework.boot:spring-boot-starter-security')
增加用户名密码登录限制。application.yml增加配置信息。
security:
basic:
path: /swagger-ui.html
enabled: true
user:
name: lifeccp
password: lifeccp
application.yml完整配置文件
#配置服务信息
#配置服务信息
server:
address: localhost
context-path: /demoService
port: 8080
spring:
profiles.active: dev
---
spring:
profiles: dev
swagger:
enable: false
security:
basic:
path: /swagger-ui.html
enabled: true
user:
name: lifeccp
password: lifeccp
---
---
spring:
profiles: test
swagger:
enable: true
security:
basic:
path: /swagger-ui.html
enabled: true
user:
name: lifeccp
password: lifeccp
---
---
spring:
profiles: prod
swagger:
enable: true
security:
basic:
path: /swagger-ui.html
enabled: true
user:
name: lifeccp
password: lifeccp
---
---
5.拦截器拦截swagger url问题。
为了防止自定义拦截器拦截swagger地址。需要增加拦截器配置。
package com.example.demo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Configuration
@Profile({"dev","prod", "test"})
public class ServletConfig extends WebMvcConfigurationSupport {
private static final Logger LOG = LoggerFactory.getLogger(ServletConfig.class);
private static final String[] EXCLUE_PATH = {"/swagger-resources/**", "/webjars/**", "/swagger-ui.html/**"};
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new HandlerInterceptorAdapter() {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String sessionid = request.getHeader("SESSIONID");
if (StringUtils.isEmpty(sessionid)) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return false;
}
LOG.info("got sessionid : {}", sessionid);
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}).addPathPatterns("/**").excludePathPatterns(EXCLUE_PATH);
}
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
二、swagger注解
常用的注解在这里列举一下,详细的需求还是要去看文档。
//用在类上,说明该类的作用。
@Api(tags = "会诊记录相关api")
//用在方法上,给API增加方法说明。
@ApiOperation(value="Get测试", notes="Get类型测试")
//用来注解来给方法入参增加说明。
@ApiImplicitParam(name = "id", value = "会诊id", required = true, dataType = "int", paramType = "path")
//用在方法上包含一组参数说明。
@ApiImplicitParams({
@ApiImplicitParam(paramType="path", name = "id", value = "记录id", required = true, dataType = "Integer"),
@ApiImplicitParam(paramType="query", name = "name", value = "记录名称", required = true, dataType = "String"),
})
//用在方法上设置reponse数据格式
@ApiResponses({@ApiResponse(code = 200,response = UserInfoDTO.class, message = "success")})
//用在对象上
@ApiModel(value = "用户对象")
@ApiModelProperty(value = "id")
@ApiModel(value = "用户对象")
public class UserInfoDTO {
@ApiModelProperty(value = "id")
private int id ;
@ApiModelProperty(value = "用户姓名")
private String name ;
@ApiModelProperty(value = "昵称")
private String nickName ;
set() ...
get() ...
}
API完整代码
@RestController
@EnableAutoConfiguration
@Api(tags = "Demo相关api")
public class SampleController {
@Value("${server.address}")
private String address ;
@Value("${server.port}")
private String port ;
@RequestMapping(value = "/sample/{id}",method = RequestMethod.GET)
@ApiOperation(value="Get测试", notes="Get类型测试")
@ApiImplicitParams({
@ApiImplicitParam(paramType="path", name = "id", value = "记录id", required = true, dataType = "Integer"),
@ApiImplicitParam(paramType="query", name = "name", value = "记录名称", required = true, dataType = "String"),
})
String home(@PathVariable("id")String id,@RequestParam("name")String name){
try{
if(Integer.parseInt(id) > 10){
return "number" ;
}
}catch (Exception e){
return "error" ;
}
return "helloworld" ;
}
@RequestMapping(value = "/sample",method = RequestMethod.POST)
@ResponseBody
@ApiOperation(value="POST测试", notes="POST类型测试")
Object testPost(@RequestBody UserInfoDTO userInfoDTO){
return userInfoDTO ;
}
}
Demo:https://github.com/xinzhongyi/SpringBootExample/tree/master/swagger-demo
三、Swagger一键导入Postman
Postman是一款http请求测试软件,不知道的同学可以自己去百度并下载使用下。
Postman可以导入Swagger的api请求,这样就不用一个一个去录入了,录入到Postman后可以利用Postman的自动化测试工具,后续还可以使用jenkins自动化继承Postman接口测试。
上图的地址填入下图中红框圈住的地址即可。
四、Postman 测试
以下只是使用了一个最简单的测试,Postman还有很多其他功能,具体可以参考官方文档。
官方文档地址:https://learning.getpostman.com/docs/postman/scripts/test_examples/
创建测试api,我是利用本机地址测试。测试api如下。
http://localhost:8080/demoService/sample/{{id}}
Tests测试用例如下
tests["result is"] = responseBody === data.result
测试数据如下,id参数可以从文件中获取,这样就不用每次手动去改。
[{
"id": "1",
"result": "helloworld"
}, {
"id": "post",
"result": "error"
}, {
"id": "20",
"result": "number"
}]
上面都是为测试准备的数据,下面开始进行Postman测试。
五、newman集成postman测试
windows安装newman,首先你得现有node环境跟npm命令。
npm install -g newman
newman run test.postman_collection -d data.json
newman run test.postman_collection -d data.json -r html --reporter-html-export ./testReport.html
测试并且声称测试报告
六、jenkins集成postman测试
未测试过jenkins集成测试,jenkins也是去执行newman命令执行测试。