使用swagger(xiaoymin版本)生成进行单元测试

一.swagger是什么?

1.支持 API 自动生成同步的在线文档:使用 Swagger 后可以直接通过代码生成文档,不再需要自己手动编写接口文档了,对程序员来说非常方便,可以节约写文档的时间去学习新技术。
2.提供 Web 页面在线测试 API:光有文档还不够,Swagger 生成的文档还支持在线测试。参数和格式都定好了,直接在界面上输入参数对应的值即可在线测试接口。

二.swagger配置与使用

1.引入依赖

<!-- swagger start -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
   <groupId>com.github.xiaoymin</groupId>
   <artifactId>swagger-bootstrap-ui</artifactId>
   <version>1.9.6</version>
</dependency>
<!-- swagger end -->

2.加入配置类

@Configuration
@EnableSwagger2
@ConditionalOnProperty(
    name = {"swagger.enable"},
    havingValue = "true"
)
public class Swagger2Config {
    @Value("${swagger.title}")
    private String title;
    @Value("${swagger.base.package}")
    private String basePackage;
    @Value("${swagger.description}")
    private String description;
    @Value("${swagger.url}")
    private String url;
    @Value("${swagger.contact.name}")
    private String contactName;
    @Value("${swagger.contact.url}")
    private String contactUrl;
    @Value("${swagger.contact.email}")
    private String contactEmail;
    @Value("${swagger.version}")
    private String version;

    public Swagger2Config() {
    }

    @Bean
    public Docket createRestApi() {
        return (new Docket(DocumentationType.SWAGGER_2)).apiInfo(this.apiInfo()).select().apis(RequestHandlerSelectors.basePackage(this.basePackage)).paths(PathSelectors.any()).build().globalOperationParameters(this.setHeaderToken());
    }

    private ApiInfo apiInfo() {
        return (new ApiInfoBuilder()).title(this.title).description(this.description).termsOfServiceUrl(this.url).contact(new Contact(this.contactName, this.contactUrl, this.contactEmail)).version(this.version).build();
    }

    private List<Parameter> setHeaderToken() {
        List<Parameter> pars = new ArrayList();
        String testTokenValue = "";
        ParameterBuilder tokenPar = new ParameterBuilder();
        Parameter tokenParameter = tokenPar.name("token").description("Token Request Header").modelRef(new ModelRef("string")).parameterType("header").required(false).defaultValue(testTokenValue).build();
        pars.add(tokenParameter);
        return pars;
    }
}

3.controller加入注解

@Slf4j
@RestController
@RequestMapping("/zntsSendInfo")
@Api(tags="推送内容信息表 API",description = "提供推送内容信息表相关的 Rest API")
public class ZntsSendInfoController extends BaseController {
    /**
     * 添加推送内容信息表
     */
    @PostMapping("/add")
    @ApiOperation(value = "添加ZntsSendInfo对象", notes = "添加推送内容信息表")
    public ApiResult<Boolean> addZntsSendInfo(@Valid @RequestBody ZntsSendInfo zntsSendInfo) throws Exception {
        boolean flag = zntsSendInfoServiceImpl.saveZntsSendInfo(zntsSendInfo);
        //noinspection unchecked
        return ApiResult.result(flag);
    }
    }

4.实体类加注解

@Data
@Accessors(chain = true)
@EqualsAndHashCode(callSuper = true)
@ApiModel(value = "ZntsSendInfo对象", description = "推送内容信息表")
public class ZntsSendInfo extends BaseEntity {

    private static final long serialVersionUID = 1L;

                    @ApiModelProperty(value = "主键",required =true)
            @TableId(value = "id", type = IdType.ID_WORKER)
    private Long id;

                    @ApiModelProperty(value = "目标类型;")
            private String targetType;

                    @ApiModelProperty(value = "目标信息")
            private String targetInfo;

                    @ApiModelProperty(value = "推送状态;")
            private String sendStatus;

                    @ApiModelProperty(value = "发送时间")
            private Date sendTime;
            }

5.application.yml配置文件

# swagger配置
swagger:
  enable: true
  base:
    package: com.sinosoft.springbootplus
  contact:
    email: zhangsan@168.com
    name: 张三
    url: ''
  description: ''
  title: 
  url: ''
  version: 1.0

6.查看api问题、单元测试
使用 http://ip:端口号/doc.html。这个版本是是用了xiaoymin的swagger,它的页面是这样的
在这里插入图片描述
调试页面在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用 Springfox 来集成 Swagger 和 Knife4j。Springfox 是一个用于构建 Swagger UI 和 Knife4j UI 的库。可以通过简单的配置,将 Swagger 和 Knife4j 集成到 Spring Boot 项目中。 ### 回答2: Spring Boot 集成 Swagger 和 Knife4j 的步骤如下: 1. 在项目的 pom.xml 文件中添加相关依赖: ```xml <!-- Swagger2 依赖 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency> <!-- Knife4j 依赖 --> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-spring-boot-starter</artifactId> <version>3.0.1</version> </dependency> ``` 2. 在项目的启动类上增加注解 `@EnableSwagger2`。 ```java @SpringBootApplication @EnableSwagger2 public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 3. 配置 Swagger 相关参数,创建一个配置类(如 SwaggerConfig)。 ```java @Configuration public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.example.demo")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("API 文档") .description("示例项目的API文档") .version("1.0.0") .build(); } } ``` 4. 在浏览器中访问 Swagger 文档,URL 一般为 `http://localhost:8080/swagger-ui.html`,通过 Swagger 可以查看和测试 API 接口。 5. 如需使用 Knife4j 的增强功能,修改 Swagger 配置类中的 `Docket` 为 `Knife4jDocket`。 ```java @Configuration public class SwaggerConfig { @Bean public Knife4jDocket knife4jDocket() { return new Knife4jDocket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.example.demo")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("API 文档") .description("示例项目的API文档") .version("1.0.0") .build(); } } ``` 经过以上步骤,就可以成功集成 Swagger 和 Knife4j,通过 Swagger 可以方便地查看和测试 API 接口文档,同时 Knife4j 提供了更多的增强功能,可以更好地管理和展示 API 接口文档。 ### 回答3: 在Spring Boot中集成Swagger和Knife4j的步骤如下: 1. 添加依赖: 在Maven的pom.xml文件中,添加以下依赖: ```xml <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-spring-boot-starter</artifactId> <version>2.0.2</version> </dependency> ``` 2. 创建Swagger配置类: 创建一个Swagger配置类,用于配置Swagger的相关参数。可以参考以下示例代码: ```java 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.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.example.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("API文档") .description("API文档") .version("1.0") .build(); } } ``` 3. 配置Knife4j的扩展设置: 创建一个Knife4j配置类,用于配置Knife4j的相关参数。可以参考以下示例代码: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc; @Configuration @EnableSwagger2WebMvc public class Knife4jConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("doc.html") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); } @Bean public Knife4jProperties knife4jProperties() { Knife4jProperties properties = new Knife4jProperties(); properties.setEnableKnife4j(true); return properties; } } ``` 4. 启动应用程序: 启动Spring Boot应用程序,并访问"http://localhost:8080/swagger-ui.html",即可查看生成Swagger API文档。 总结: 通过添加相关的依赖和配置类,我们可以很容易地在Spring Boot中集成Swagger和Knife4j。Swagger用于生成API文档,而Knife4j是对Swagger的扩展,提供了更丰富的功能和界面。集成后,我们可以方便地查看和测试接口文档。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值