(07)使用WireMock快速伪造REST服务

  WireMock功能强大,本文记录一下它一个基础功能,快速伪造REST服务。

  1、下载WireMock独立运行包

  进入官网http://wiremock.org,点击Docs,Running as a Standalone,点击downloaded the standalone JAR下载

  

  

  2、运行jar包,启动WireMock服务

  进入包所在文件夹,指定端口,运行一下命令:

java -jar wiremock-standalone-2.26.3.jar --port 9062

  

  3、演示效果

  1)添加依赖 

<dependency>
    <groupId>com.github.tomakehurst</groupId>
    <artifactId>wiremock</artifactId>
    <version>2.5.1</version>
    <type>pom</type>
    <scope>test</scope>
</dependency>

  2)测试方法

public class MockServer {

    public static void main(String[] args) {
        WireMock.configureFor(9062);
        WireMock.removeAllMappings();
        WireMock.stubFor(WireMock.get(WireMock.urlPathEqualTo("/order/1"))
                                 .willReturn(WireMock.aResponse().withBody("{"id":1}").withStatus(200)));
    }
}

  运行main方法,浏览器输入:http://localhost:9062/order/1,显示:{"id":1},访问成功。

  现在是在类中写返回的json串,下面改为在txt文件中设置返回的json串。

public class MockServer {

    public static void main(String[] args) throws IOException {
        WireMock.configureFor(9062);
        WireMock.removeAllMappings();
        mock("/order/1","01");
        mock("/order/2","02");
    }
    
    private static void mock(String url,String file) throws IOException {
        ClassPathResource source = new ClassPathResource("com/edu/sl/wiremock/response/"+file+".txt");
        List<String> list = FileUtils.readLines(source.getFile(),"UTF-8");
        String content = StringUtils.join(list,"
".charAt(0));
        WireMock.stubFor(WireMock.get(WireMock.urlPathEqualTo(url))
                                 .willReturn(WireMock.aResponse().withBody(content).withStatus(200)));
    }
}

  在com/edu/sl/wiremock/response目录下,新建01.txt、02.txt

{
    "id":1,
    "type":"A"
}
{
    "id":2,
    "type":"AC"
}

  重新运行一下main函数,将结果刷到WireMock服务器中,在浏览器访问:

  http://localhost:9062/order/1,页面显示01.txt的内容

  http://localhost:9062/order/2,页面显示02.txt的内容

原文地址:https://www.cnblogs.com/javasl/p/12994220.html