SpringBoot集成Swagger,Postman,newman,jenkins自动化测试.

环境: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<Parameter> pars = new ArrayList<Parameter>();
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();
}

<span class="hljs-keyword">private</span> <span class="hljs-type">ApiInfo</span> apiInfo() {
    <span class="hljs-keyword">return</span> new <span class="hljs-type">ApiInfoBuilder</span>()
            .title(<span class="hljs-string">"springboot利用swagger构建api文档"</span>)
            .description(<span class="hljs-string">"简单优雅的restfun风格"</span>)
            .version(<span class="hljs-string">"1.0"</span>)
            .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/**"};

<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">addInterceptors</span><span class="hljs-params">(InterceptorRegistry registry)</span> </span>{
    registry.addInterceptor(<span class="hljs-keyword">new</span> HandlerInterceptorAdapter() {

        <span class="hljs-meta">@Override</span>
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">preHandle</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response, Object handler)</span> <span class="hljs-keyword">throws</span> Exception </span>{
            String sessionid = request.getHeader(<span class="hljs-string">"SESSIONID"</span>);

            <span class="hljs-keyword">if</span> (StringUtils.isEmpty(sessionid)) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;
            }

            LOG.info(<span class="hljs-string">"got sessionid : {}"</span>, sessionid);
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">true</span>;
        }

        <span class="hljs-meta">@Override</span>
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">afterCompletion</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)</span> <span class="hljs-keyword">throws</span> Exception </span>{

        }
    }).addPathPatterns(<span class="hljs-string">"/**"</span>).excludePathPatterns(EXCLUE_PATH);
}

<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">addResourceHandlers</span><span class="hljs-params">(ResourceHandlerRegistry registry)</span> </span>{
    registry.addResourceHandler(<span class="hljs-string">"swagger-ui.html"</span>)
            .addResourceLocations(<span class="hljs-string">"classpath:/META-INF/resources/"</span>);
    registry.addResourceHandler(<span class="hljs-string">"/webjars/**"</span>)
            .addResourceLocations(<span class="hljs-string">"classpath:/META-INF/resources/webjars/"</span>);
}

}

二、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 {
<span class="hljs-meta">@Value</span>(<span class="hljs-string">"<span class="hljs-subst">${server.address}</span>"</span>)
private <span class="hljs-built_in">String</span> address ;

<span class="hljs-meta">@Value</span>(<span class="hljs-string">"<span class="hljs-subst">${server.port}</span>"</span>)
private <span class="hljs-built_in">String</span> port ;

<span class="hljs-meta">@RequestMapping</span>(value = <span class="hljs-string">"/sample/{id}"</span>,method = RequestMethod.GET)
<span class="hljs-meta">@ApiOperation</span>(value=<span class="hljs-string">"Get测试"</span>, notes=<span class="hljs-string">"Get类型测试"</span>)
<span class="hljs-meta">@ApiImplicitParams</span>({
        <span class="hljs-meta">@ApiImplicitParam</span>(paramType=<span class="hljs-string">"path"</span>, name = <span class="hljs-string">"id"</span>, value = <span class="hljs-string">"记录id"</span>, required = <span class="hljs-keyword">true</span>, dataType = <span class="hljs-string">"Integer"</span>),
        <span class="hljs-meta">@ApiImplicitParam</span>(paramType=<span class="hljs-string">"query"</span>, name = <span class="hljs-string">"name"</span>, value = <span class="hljs-string">"记录名称"</span>, required = <span class="hljs-keyword">true</span>, dataType = <span class="hljs-string">"String"</span>),
})
<span class="hljs-built_in">String</span> home(<span class="hljs-meta">@PathVariable</span>(<span class="hljs-string">"id"</span>)<span class="hljs-built_in">String</span> id,<span class="hljs-meta">@RequestParam</span>(<span class="hljs-string">"name"</span>)<span class="hljs-built_in">String</span> name){
    <span class="hljs-keyword">try</span>{
        <span class="hljs-keyword">if</span>(Integer.parseInt(id) &gt; <span class="hljs-number">10</span>){
            <span class="hljs-keyword">return</span> <span class="hljs-string">"number"</span> ;
        }
    }<span class="hljs-keyword">catch</span> (Exception e){
        <span class="hljs-keyword">return</span> <span class="hljs-string">"error"</span> ;
    }
    <span class="hljs-keyword">return</span> <span class="hljs-string">"helloworld"</span> ;
}

<span class="hljs-meta">@RequestMapping</span>(value = <span class="hljs-string">"/sample"</span>,method = RequestMethod.POST)
<span class="hljs-meta">@ResponseBody</span>
<span class="hljs-meta">@ApiOperation</span>(value=<span class="hljs-string">"POST测试"</span>, notes=<span class="hljs-string">"POST类型测试"</span>)
<span class="hljs-built_in">Object</span> testPost(<span class="hljs-meta">@RequestBody</span> UserInfoDTO userInfoDTO){
    <span class="hljs-keyword">return</span> 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命令执行测试。
在这里插入图片描述

           本文链接:https://blog.csdn.net/zhuguanghalo/article/details/90673592                     </div>
posted @ 2019-09-10 11:48  星朝  阅读(979)  评论(0编辑  收藏  举报