使用WireMock 伪造 Rest 服务

WireMock 是基于 HTTP 的模拟器。它具备 HTTP 响应存根、请求验证、代理/拦截、记录和回放功能。
当开发人员的开发进度不一致时,可以依赖 WireMock 构建的接口,模拟不同请求与响应,从而避某一模块的开发进度。

官方文档:http://wiremock.org/docs/running-standalone/

1. 搭建wireMock单机服务

1.1 下载jar包

服务jar包下载:http://repo1.maven.org/maven2/com/github/tomakehurst/wiremock-standalone/2.14.0/wiremock-standalone-2.14.0.jar

1.2 启动jar

java -jar wiremock-standalone-2.14.0.jar --port 9000
我在这里用9000端口启动

使用WireMock 伪造 Rest 服务_第1张图片

好了,看到上面的图案说明服务就搭建好了。

2. 向服务里注册Rest服务

2.1 导入依赖
        
            com.github.tomakehurst
            wiremock
        
2.2 写一个简单的模拟Rest
/**
 * Created by Fant.J.
 */
public class MockServer {
    public static void main(String[] args) {
        //通过端口连接服务
        WireMock.configureFor(9000);
        //清空之前的配置
        WireMock.removeAllMappings();

        //get请求
        WireMock.stubFor(WireMock.get(WireMock.urlPathEqualTo("/user/1"))
                .willReturn(WireMock.aResponse()
                 //body里面写 json
                .withBody("{\"username\":FantJ}")
                 //返回状态码
                .withStatus(200)));

    }
}

运行这个main方法。

使用WireMock 伪造 Rest 服务_第2张图片

然后访问 http://127.0.0.1:9000/user/1
使用WireMock 伪造 Rest 服务_第3张图片

企业级开发封装

/**
 * Created by Fant.J.
 */
public class MockServer {
    public static void main(String[] args) throws IOException {
        //通过端口连接服务
        WireMock.configureFor(9000);
        //清空之前的配置
        WireMock.removeAllMappings();

        //调用 封装方法
        mock("/user/2","user");


    }

    private static void mock(String url, String filename) throws IOException {
        ClassPathResource resource = new ClassPathResource("/wiremock/"+filename+".txt");
        String content = FileUtil.readAsString(resource.getFile());

        //get请求
        WireMock.stubFor(WireMock.get(WireMock.urlPathEqualTo(url))
                .willReturn(WireMock.aResponse()
                        //body里面写 json
                        .withBody(content)
                        //返回状态码
                        .withStatus(200)));
    }
}

其中,user.txt文件在这里



文本内容:


使用WireMock 伪造 Rest 服务_第4张图片

然后我们运行程序,访问http://127.0.0.1:9000/user/2

使用WireMock 伪造 Rest 服务_第5张图片

介绍下我的所有文集:

流行框架

SpringCloud
springboot
nginx
redis

底层实现原理:

Java NIO教程
Java reflection 反射详解
Java并发学习笔录
Java Servlet教程
jdbc组件详解
Java NIO教程
Java语言/版本 研究

你可能感兴趣的:(使用WireMock 伪造 Rest 服务)