SpringBoot集成Swagger,Postman,newman,jenkins自動(dòng)化測試.

環(huán)境:Spring Boot,Swagger,gradle,Postman,newman,jenkins
SpringBoot環(huán)境搭建。
Swagger簡介
Swagger 是一款RESTFUL接口的文檔在線自動(dòng)生成+功能測試功能軟件。


image.png

一、SpringBoot集成Swagger

1.build.gradle增加swagger相關(guān)jar包,maven項(xiàng)目同理。

image.png

2.增加SwaggerConfig配置文件。

前兩步完成,訪問http://localhost:8080/demoService/swagger-ui.html#/即可看見swagger的api頁面了。下面幾個(gè)步驟是為了解決一些配置問題,沒有以下幾種問題可以不用配置。

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());    //根據(jù)每個(gè)方法名也知道當(dāng)前方法在設(shè)置什么參數(shù)
        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構(gòu)建api文檔")
                .description("簡單優(yōu)雅的restfun風(fēng)格")
                .version("1.0")
                .build();
    }

}
image.png

3.生產(chǎn)環(huán)境不部署問題

解決生產(chǎn)環(huán)境不部署問題,application.yml增加配置信息。SwaggerConfig增加注解信息,完整配置文件信息在下方。
swagger.enable

image.png

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完整配置文件

#配置服務(wù)信息
#配置服務(wù)信息
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注解

常用的注解在這里列舉一下,詳細(xì)的需求還是要去看文檔。

//用在類上,說明該類的作用。
@Api(tags = "會(huì)診記錄相關(guān)api")
//用在方法上,給API增加方法說明。
@ApiOperation(value="Get測試", notes="Get類型測試")
//用來注解來給方法入?yún)⒃黾诱f明。
@ApiImplicitParam(name = "id", value = "會(huì)診id", required = true, dataType = "int", paramType = "path")
//用在方法上包含一組參數(shù)說明。
@ApiImplicitParams({
            @ApiImplicitParam(paramType="path", name = "id", value = "記錄id", required = true, dataType = "Integer"),
            @ApiImplicitParam(paramType="query", name = "name", value = "記錄名稱", required = true, dataType = "String"),
    })
//用在方法上設(shè)置reponse數(shù)據(jù)格式
@ApiResponses({@ApiResponse(code = 200,response = UserInfoDTO.class, message = "success")})

//用在對(duì)象上
@ApiModel(value = "用戶對(duì)象")
@ApiModelProperty(value = "id")

@ApiModel(value = "用戶對(duì)象")
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相關(guān)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一鍵導(dǎo)入Postman

Postman是一款http請(qǐng)求測試軟件,不知道的同學(xué)可以自己去百度并下載使用下。
Postman可以導(dǎo)入Swagger的api請(qǐng)求,這樣就不用一個(gè)一個(gè)去錄入了,錄入到Postman后可以利用Postman的自動(dòng)化測試工具,后續(xù)還可以使用jenkins自動(dòng)化繼承Postman接口測試。

image.png
image.png

上圖的地址填入下圖中紅框圈住的地址即可。

image.png
image.png

四、Postman 測試

以下只是使用了一個(gè)最簡單的測試,Postman還有很多其他功能,具體可以參考官方文檔。
官方文檔地址:https://learning.getpostman.com/docs/postman/scripts/test_examples/

創(chuàng)建測試api,我是利用本機(jī)地址測試。測試api如下。
http://localhost:8080/demoService/sample/{{id}}
Tests測試用例如下
tests["result is"] = responseBody === data.result
測試數(shù)據(jù)如下,id參數(shù)可以從文件中獲取,這樣就不用每次手動(dòng)去改。

[{
  "id": "1",
  "result": "helloworld"
}, {
  "id": "post",
  "result": "error"
}, {
  "id": "20",
  "result": "number"
}]

上面都是為測試準(zhǔn)備的數(shù)據(jù),下面開始進(jìn)行Postman測試。


創(chuàng)建測試API
打開測試用例界面
選擇測試數(shù)據(jù)文件
查看測試數(shù)據(jù)信息
測試結(jié)束

五、newman集成postman測試

windows安裝newman,首先你得現(xiàn)有node環(huán)境跟npm命令。
npm install -g newman

newman

newman run test.postman_collection -d data.json

執(zhí)行測試計(jì)劃

newman run test.postman_collection -d data.json -r html --reporter-html-export ./testReport.html
測試并且聲稱測試報(bào)告

測試報(bào)告

六、jenkins集成postman測試

未測試過jenkins集成測試,jenkins也是去執(zhí)行newman命令執(zhí)行測試。


jenkins集成
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,443評(píng)論 6 532
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,530評(píng)論 3 416
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,407評(píng)論 0 375
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,981評(píng)論 1 312
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,759評(píng)論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,204評(píng)論 1 324
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,263評(píng)論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,415評(píng)論 0 288
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,955評(píng)論 1 336
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,782評(píng)論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 42,983評(píng)論 1 369
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,528評(píng)論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,222評(píng)論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,650評(píng)論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,892評(píng)論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 51,675評(píng)論 3 392
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 47,967評(píng)論 2 374

推薦閱讀更多精彩內(nèi)容