配置Mock响应规则

会通过 __filesmappings 目录来存放匹配规则文件。 匹配文件以 json 格式存放在 mappings 目录下,WireMock 会在启动后自动加载该目录下所有符合格式的文件作为匹配规则使用。

基本匹配格式

1
2
3
4
5
6
7
8
9
10
{
"request": {
"method": "GET",
"url": "/api/book/abc"
},
"response": {
"status": 200,
"body": "this is a book"
}
}

消息头

  • 可以在 request 或 response 中定义 headers 来匹配请求或者指定响应消息头。
1
2
3
4
"headers": {
"Content-Type": "text/plain",
"Cache-Control": "no-cache"
}

消息体

  • 除了上面直接在 reponse 中通过 body 来直接定义响应消息体。对于 json 格式的响应可以利用 jsonBody 来直接定义

    1
    2
    3
    4
    5
    6
    "response": {
    "status": 200,
    "jsonBody": {
    "arbitrary_json": [1, 2, 3]
    }
    }
  • 或者使用 bodyFileName 来指定文件内容作为响应消息体,消息体文件默认存放在 __files目录下

    1
    2
    3
    4
    "response": {
    "status": 200,
    "bodyFileName": "filebody.json"
    }

消息优先级

  • WireMock 支持指定匹配规则的消息优先级,当请求存在多个符合条件的响应时,可以根据优先级关键字 priority 来选择优先匹配的响应。优先级从 1 到 10, 1 优先级最高。
  • 这个特性很有用,我们可以把一些默认匹配设置为低优先级,这样能保证请求的基本匹配。如下面示例就是一个通用的默认返回配置:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
"priority":10,
"request": {
"method": "ANY",
"urlPattern": ".*"
},
"response": {
"status": 404,
"jsonBody": {"status":"Error","message":"Endpoint not found"},
"headers": {
"Content-Type": "application/json"
}
}
}

场景配置

  • WireMock 中另一个很有用的高级特性是支持场景配置,场景是通过状态机来触发,默认状态是 STARTED,通过设置场景(设置 scenarioName )可以在触发后变更新的状态(设置 requiredScenarioState),并根据新的状态(设置 requiredScenarioState )来实现灵活匹配。比如下例就是一个对同一地址重复发送请求返回不同响应的场景配置。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
{
"scenarioName": "doubleSend",
"requiredScenarioState": "Started",
"newScenarioState": "Sent",
"request": {
"method": "GET",
"url": "/send/messge"
},
"response": {
"status": 200,
"body" : "第一次发送"
}
}

{
"scenarioName": "doubleSend",
"requiredScenarioState": "Sent",
"request": {
"method": "GET",
"url": "/send/messge"
},
"response": {
"status": 200,
"body" : "第二次发送"
}
}