如何使用Springfox Swagger实现API自动生成单元测试

 更新时间:2024年04月11日 10:55:05   作者:W-琑  
Springfox是一个使用Java语言开发开源的API Doc的框架,它的前身是swagger-springmvc,可以将我们的Controller中的方法以文档的形式展现,这篇文章主要介绍了如何使用Springfox Swagger实现API自动生成单元测试,感兴趣的朋友跟随小编一起看看吧

Springfox 简介

Springfox 是一个使用Java语言开发开源的API Doc的框架, 它的前身是swagger-springmvc,可以将我们的Controller中的方法以文档的形式展现。官方定义为: Automated JSON API documentation for API’s built with Spring。

Springfox 目前有1、2、3三种版本,从v3版本开始则有较大变化,据官方文档介绍,变化如下:

删除早期版本的一些依赖。特别是删除springfox-swagger2和springfox-swagger-ui依赖。

  • 删除 @EnableSwagger2 注释
  • 添加 springfox-boot-starter 支持springboot使用的起步依赖
  • Springfox 3.x 删除了对 guava 和其他第三方库的依赖(但仍然依赖于 spring 插件和开放 api 库,用于注释和模型)

Springfox 的作用

1)将前后端有效分离,并保证了API与文档的实时同步
2)使用springfox生成的接口文档直观可视,支持查看各个接口需要的参数和返回结果
3)springfox支持在线测试,可实时检查参数和返回值

接下来介绍如何使用Springfox Swagger实现API自动生成单元测试。

第一步:在pom.xml中添加依赖

        <!-- API⽂档⽣成,基于swagger2 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>
        <!-- SpringBoot健康监控 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

第二步:加入以下代码,并作出适当修改

package com.bitejiuyeke.forum.config;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.CorsEndpointProperties;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties;
import org.springframework.boot.actuate.autoconfigure.web.server.ManagementPortType;
import org.springframework.boot.actuate.endpoint.ExposableEndpoint;
import org.springframework.boot.actuate.endpoint.web.*;
import org.springframework.boot.actuate.endpoint.web.annotation.ControllerEndpointsSupplier;
import org.springframework.boot.actuate.endpoint.web.annotation.ServletEndpointsSupplier;
import org.springframework.boot.actuate.endpoint.web.servlet.WebMvcEndpointHandlerMapping;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
 * Swagger配置类
 */
// 配置类
@Configuration
// 开启Springfox-Swagger
@EnableOpenApi
public class SwaggerConfig {
    /**
     * Springfox-Swagger基本配置
     * @return
     */
    @Bean
    public Docket createApi() {
        Docket docket = new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.btjyk.forum.controller")) //根据自己controller包的 路径自行修改
                .paths(PathSelectors.any())
                .build();
        return docket;
    }
    // 配置API基本信息
    private ApiInfo apiInfo() {//以下 基本信息均可修改
        ApiInfo apiInfo = new ApiInfoBuilder()
                .title("线上论坛系统API")
                .description("线上论坛系统前后端分离API测试")
                .contact(new Contact("Bit Tech",
                        "https://edu.btjyk.com", "1598374550@qq.com"))
                .version("1.0")
                .build();
        return apiInfo;
    }
    /**
     * 解决SpringBoot 6.0以上与Swagger 3.0.0 不兼容的问题
     * 复制即可
     **/
    @Bean
    public WebMvcEndpointHandlerMapping
    webEndpointServletHandlerMapping(WebEndpointsSupplier webEndpointsSupplier,
                                     ServletEndpointsSupplier servletEndpointsSupplier,
                                     ControllerEndpointsSupplier controllerEndpointsSupplier,
                                     EndpointMediaTypes endpointMediaTypes, CorsEndpointProperties corsProperties,
                                     WebEndpointProperties webEndpointProperties, Environment environment) {
        List<ExposableEndpoint<?>> allEndpoints = new ArrayList();
        Collection<ExposableWebEndpoint> webEndpoints =
                webEndpointsSupplier.getEndpoints();
        allEndpoints.addAll(webEndpoints);
        allEndpoints.addAll(servletEndpointsSupplier.getEndpoints());
        allEndpoints.addAll(controllerEndpointsSupplier.getEndpoints());
        String basePath = webEndpointProperties.getBasePath();
        EndpointMapping endpointMapping = new EndpointMapping(basePath);
        boolean shouldRegisterLinksMapping =
                this.shouldRegisterLinksMapping(webEndpointProperties, environment,
                        basePath);
        return new WebMvcEndpointHandlerMapping(endpointMapping, webEndpoints,
                endpointMediaTypes,
                corsProperties.toCorsConfiguration(), new
                EndpointLinksResolver(allEndpoints, basePath),
                shouldRegisterLinksMapping, null);
    }
    private boolean shouldRegisterLinksMapping(WebEndpointProperties webEndpointProperties, Environment environment, String basePath) {
        return webEndpointProperties.getDiscovery().isEnabled()
                && (StringUtils.hasText(basePath)
                || ManagementPortType.get(environment).equals(ManagementPortType.DIFFERENT));
    }
}

第三步:在application.yaml中添加

spring
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher #Springfox-Swagger兼容性配置

第四步:添加注解

  • @Api: 作⽤在Controller上,对控制器类的说明 。tags="说明该类的作⽤,可以在前台界⾯上看到的注解"
  • @ApiModel: 作⽤在响应的类上,对返回响应数据的说明
  • @ApiModelProerty:作⽤在类的属性上,对属性的说明
  • @ApiOperation: 作⽤在具体⽅法上,对API接⼝的说明
  • @ApiParam:作⽤在⽅法中的每⼀个参数上,对参数的属性进⾏说明

启动程序,浏览器中输⼊地址:http://127.0.0.1:端口号/swagger-ui/index.html ,可以正常并 显⽰接⼝信息,说明配置成功,此时接⼝信息已经显⽰出来了,可以分别针对每个接⼝进⾏测试,具 体操作按⻚⾯指引即可。

另外:还可以导出到postman

1.复制

2.打开postman

3.粘贴

4.点击import即可

到此这篇关于如何使用Springfox Swagger实现API自动生成单元测试的文章就介绍到这了,更多相关Springfox Swagger 单元测试内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java JDK动态代理(AOP)的实现原理与使用详析

    Java JDK动态代理(AOP)的实现原理与使用详析

    所谓代理,就是一个人或者一个机构代表另一个人或者另一个机构采取行动。下面这篇文章主要给大家介绍了关于Java JDK动态代理(AOP)实现原理与使用的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考借鉴,下面来一起看看吧。
    2017-07-07
  • Springboot 中的 Filter 实现超大响应 JSON 数据压缩的方法

    Springboot 中的 Filter 实现超大响应 JSON 数据压缩的方法

    这篇文章主要介绍了Springboot 中的 Filter 实现超大响应 JSON 数据压缩,定义GzipFilter对输出进行拦截,定义 Controller该 Controller 非常简单,主要读取一个大文本文件,作为输出的内容,本文通过实例代码给大家介绍的非常详细,需要的朋友可以参考下
    2022-10-10
  • IntelliJ IDEA(2017)安装和破解的方法

    IntelliJ IDEA(2017)安装和破解的方法

    这篇文章主要介绍了IntelliJ IDEA(2017)安装和破解的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-11-11
  • Java使用iTextPDF生成PDF文件的实现方法

    Java使用iTextPDF生成PDF文件的实现方法

    这篇文章主要介绍了Java使用iTextPDF生成PDF文件的实现方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-02-02
  • Spring简明分析Bean作用域

    Spring简明分析Bean作用域

    scope用来声明容器中的对象所应该处的限定场景或者说该对象的存活时间,即容器在对象进入其 相应的scope之前,生成并装配这些对象,在该对象不再处于这些scope的限定之后,容器通常会销毁这些对象,这篇文章主要介绍了Spring中的Bean作用域,需要的朋友可以参考下
    2022-07-07
  • SpringBoot容器的主要组件详解

    SpringBoot容器的主要组件详解

    这篇文章主要介绍了SpringBoot容器的主要组件详解,SpringBoot 是基于 Spring Framework 的一种快速开发框架,它可以帮助开发者快速地构建独立的、生产级别的、可部署的应用程序,需要的朋友可以参考下
    2023-09-09
  • 应用启动数据初始化接口CommandLineRunner和Application详解

    应用启动数据初始化接口CommandLineRunner和Application详解

    这篇文章主要介绍了应用启动数据初始化接口CommandLineRunner和Application详解,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-12-12
  • mybatis的insert插入后获取自增id的方法详解(从controller到mapper)

    mybatis的insert插入后获取自增id的方法详解(从controller到mapper)

    这篇文章主要介绍了mybatis的insert插入后获取自增id的示例代码,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-10-10
  • 从入门到精通:Java List遍历修改的完全指南

    从入门到精通:Java List遍历修改的完全指南

    在Java中,我们经常需要遍历List集合并对其中的元素进行修改,这可以通过使用迭代器或for循环来实现,需要的朋友可以参考下
    2023-10-10
  • Java如何使用Set接口存储没有重复元素的数组

    Java如何使用Set接口存储没有重复元素的数组

    Set是一个继承于Collection的接口,即Set也是集合中的一种。Set是没有重复元素的集合,本篇我们就用它存储一个没有重复元素的数组
    2022-04-04

最新评论