WireMock 介绍

WireMock 是一个 Http 模拟服务,其核心是 web 服务,WireMock 可以为特定的请求(stubbing)提供固定的响应,并捕获传入的请求,以便后面校验(验证)
WireMock 可以作为第三方库在项目中使用(一般用于集成测试),也可以作为单独的进程启动(singleton),该篇文章首先介绍 singleton 的使用方式

搭建 WireMock 服务

在本地搭建 WireMock 服务,首先需要到 WireMock release page 下载最新的 jar,然后通过 java -jar 启动 WireMock 服务

$ java -jar wiremock-standalone-2.27.2.jar复制代码

也可以指定一些启动参数,比如 --port 指定服务的启动端口,更多的参数可以参考 wiremock.org/docs/runnin…

WireMock 使用

启动 WireMock 服务的时候,WireMock 默认会在当前路径下创建两个文件夹 mappings 和 __files,用于存放映射配置与服务文件

stubbing 注册

既然是模拟服务,那么肯定是要模拟一些请求响应的。可以通过 POST 调用 http://<host>:<port>/__admin/mappings 接口,向 WireMock 服务注册一个 stubbing(存根),request body 如下:

{"request": {"method": "GET","url": "/some/thing"},"response": {"status": 200,"jsonBody": {			"name": "huangxy",			"age": 12
		},"headers": {"Content-Type": "application/json"}
    }
}复制代码

表示向 WireMock 服务注册一个 stubbing,当 GET 方法调用服务的 /some/thing 接口时,服务返回 200,响应体内容为 Hello world!,响应头为 Content-Type: Text/plain

接着使用 GET 方法调用 http://localhost:8080/some/thing 接口,服务返回 {"name":"huangxy","age":12} 证明 stubbing 注册成功

$ curl http://localhost:8080/some/thing{"name":"huangxy","age":12}复制代码

除了 GET 方法,WireMock 还支持 POST PUT DELETE HEAD OPTIONS TRACE 等常见请求方式,甚至可以使用 ANY 支持所有的请求方式

通过接口调用注册 stubbing 的方式,只是把 stubbing 存放到内存中,服务重启之后 stubbing 就会被清除掉。想要持久化 stubbing 就要用到 mappings 文件夹,WireMock 在启动的时候会扫描 mappings 目录下的所有 .json 文件,然后将文件中的映射信息注册到服务中

比如,我们在 mappings 文件夹下创建 hello.json 文件,文件内容如下:

{"request": {"method": "ANY","url": "/hello"},"response": {"status": 200,"body": "Hello WireMock!","headers": {"Content-Type": "text/plain"}
    }
}复制代码

然后使用 curl 访问 /hello 接口

$ curl http://localhost:8080/helloHello WireMock!复制代码

可以看到,即使我们没有调用 __admin/mappings 接口注册 /hello 接口,服务也能正确的返回预期结果,证明服务在启动的时候确实读取了 mappings 文件夹下的内容

文件服务(file serving)

当使用 GET 请求 WireMock 的时候,服务首先会寻找匹配的 stubbing,对匹配到的请求进行响应,如果匹配不到对应的请求,WireMock 会去 __files 文件夹下寻找是否有匹配的资源,有的话将匹配到的资源返回给调用者
我们在 __files 文件夹下创建一个 index.html 文件,文件内容如下:

Hello WireMock!复制代码

重启 WireMock,访问 /index 接口,WireMock 返回 index.html 文件内容 - Hello WireMock!,证明服务在匹配不到 stubbing 的时候,确实会读取 __files 目录下的资源,将文件内容返回

请求校验

WireMock 会将运行过程中收到的所有请求记录到内存中,这样做就可以验证是否收到了某些请求,同时能获取请求的详细信息 可以通过 WireMock 的 /__admin/requests/count 端点获取请求被调用的次数,比如我们注册了一个 /hello 的 GET 请求的 stubbing

{"request": {"method": "GET","url": "/hello"},"response": {"status": 200,		"body": "hello wiremock"}
}复制代码

接着请求两次 /hello,然后 GET 调用 /__admin/request/count 端口,获取 /hello 被调用的次数,请求体内容如下

{"method": "POST","url": "/hello"}复制代码

调用成功,服务返回 /hello 被调用的次数

{"count": 2,"requestJournalDisabled": false}复制代码
总结

本文只介绍了 WireMock 的简单使用,WireMock 还有更多强大的功能,如对正则表达式的支持,返回特定的状态码(4xx,5xx)等