Swagger和WireMock的简单使用

1.Swagger自动生成HTML文档

在springboot项目中导入依赖

<!--利用Swagger生成HTML文档-->
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.8.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.8.0</version>
</dependency>

在启动类上加上@EnableSwagger2注解,启动项目,访问http://localhost:8002/swagger-ui.html

即可查看所有接口。

对接口进行描述

@RequestMapping(value = "/",method = RequestMethod.GET)
@ApiOperation("前往首页")//对Swagger2生成的接口进行一个描述
public String root(){
    return "redirect:index";
}

在实体类中对返回的数据对象的属性进行描述:

@ApiModelProperty(value="用户的介绍属性")

private String description;

在RESTful风格中解释传入的数据

@GetMapping("/{id}/deletion")
public ModelAndView delete(Model model,@PathVariable("id") @ApiParam("传入一个博客的id") Integer id){
    System.out.println("controller。。。");
    blogService.deleteBlog(id);
    model.addAttribute("blogsList",blogService.getBlogs());
    return new ModelAndView("blog/list","blogModel",model);
}

2.WireMock快速伪造RESTful服务

前端并行开发的时候,我们给它提供了一套伪造的RESTful服务,避免了app,pc端,小程序开发人员 ,对接口的理解不一致,写的假的接口不一致 ,最好不好对接后台。

swagger的使用必须在该服务开发测试好了,才能给前端来浏览swagger来调用。

1.下载,运行 jar

官网==》doc ==》running-standalone 作为一个独立服务器运行

$ java -jar wiremock-standalone-2.23.2.jar

2.在项目中添加依赖

<dependency>
    <groupId>com.github.tomakehurst</groupId>
    <artifactId>wiremock</artifactId>
    <version>2.22.0</version>
</dependency>

不要加入scope为test环境,否者在主函数中找不到jar

3.编写运行函数

import com.github.tomakehurst.wiremock.client.WireMock;
//相当于一个wiremock的客户端
public class Test {
    public static void main(String[] args) {
//        System.out.println(new BCryptPasswordEncoder().encode("123456"));
        WireMock.configureFor(8000);//连接8000端口的服务器
        WireMock.removeAllMappings();//清空以前的服务
////向服务器发送get请求的接口服务,返回json串和200状态码
        WireMock.stubFor(
                WireMock.get(
                        WireMock.urlPathEqualTo("/order/1"))
                        .willReturn(WireMock.aResponse().withBody("{\"id\":1}").withStatus(200)));
    }
}

运行在服务器上访问该伪服务接口

简化代码:

public class MockServer {

    /**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        configureFor(8062);
        removeAllMappings();

        mock("/order/1", "01");
        mock("/order/2", "02");
    }

    private static void mock(String url, String file) throws IOException {
        ClassPathResource resource = new ClassPathResource("mock/response/" + file + ".txt");
        String content = StringUtils.join(FileUtils.readLines(resource.getFile(), "UTF-8").toArray(), "\n");
        stubFor(get(urlPathEqualTo(url)).willReturn(aResponse().withBody(content).withStatus(200)));
    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章