天天看点

使用Swagger-UI进行接口测试

1.pom文件引入依赖

<!-- Swagger -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.7.0</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.7.0</version>
        </dependency>
           

2.创建配置类

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket ccaApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("task")
                .genericModelSubstitutes(DeferredResult.class)
                .useDefaultResponseMessages(false)
                .forCodeGeneration(true)
                .pathMapping("/")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.xxx.xxx.controller"))
                .paths(or(regex("/.*")))//过滤的接口
                .build()
                .apiInfo(taskApiInfo());
    }

    private ApiInfo taskApiInfo() {
        return new ApiInfoBuilder()
                .title("测试服务接口列表")//大标题
                .version("1.0")//版本
                .build();
    }
}
           

其中,.apis(RequestHandlerSelectors.basePackage(“com.xxx.xxx.controller”))配置了要扫描的包。

3.代码中添加注解

@RestController
@RequestMapping("/test")
public class TestController {

	@Autowired
	private TestService testService;
	
    @RequestMapping(path = "testFunc", method = RequestMethod.GET)
    public String testFunc(){
    	System.out.println("---:");
        return "Hello!";
    }    
}
           

4.启动服务,访问swagger-ui

使用Swagger-UI进行接口测试

@Api用于给类添加描述。

@ApiOperation用于给方法添加描述。

@ApiParam用于给单个参数添加描述。

@ApiImplicitParams用于给方法的所有参数添加描述。跟@ApiParam类似。