WireMock Java代码内集成调用

之前,已经介绍了WireMock单独启动的使用了,但WireMock 本身由 Java 语言开发,所以在 Java 中可以方便地进行调用。接下来,介绍在Java代码中如何进行WireMock的使用。

创建工程

  1. 创建maven工程

  2. 引入需要的依赖

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    <dependency>
    <groupId>com.github.tomakehurst</groupId>
    <artifactId>wiremock-jre8</artifactId>
    <version>${wiremock.version}</version>
    </dependency>

    <dependency>
    <groupId>com.github.tomakehurst</groupId>
    <artifactId>wiremock-jre8-standalone</artifactId>
    <version>${wiremock.version}</version>
    </dependency>

    <dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>4.3.0</version>
    </dependency>
  1. 编写代码

与Junit4集成调用

默认提供了和 Junit4 的集成。通过 Juit4 的 Rule 注解,可以方便地完成WireMock的匹配规则(stub)设置。

  1. 添加Junit4的依赖
1
2
3
4
5
6
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
  1. 编写代码,完成接口的Mock测试
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.wiremock.demo;

import com.github.tomakehurst.wiremock.junit.WireMockRule;
import io.restassured.RestAssured;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;

import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static io.restassured.RestAssured.given;

/**
* 在Junit4中使用WireMock来实现服务端响应模拟功能
*
* @author jingLv
* @date 2020/10/12
*/
public class WireMockForJunit4 {

/**
* 参数:port,https-port
* options().port(8088).httpsPort(8089)
* @ClassRule 定义静态的匹配规则
*/
@Rule
public WireMockRule wireMockRule = new WireMockRule(8088, 8089);

@BeforeClass
public static void setUp() {
RestAssured.baseURI = "http://localhost:8088";
}

@Test
public void test() {
// Mock接口定义匹配规则
wireMockRule.stubFor(get(urlEqualTo("/api/book/abc"))
.willReturn(aResponse()
.withBody("successful")
.withStatus(200)));

// 请求接口,验证此接口
given().when().get("/api/book/abc").then().log().all();
}
}

与Junit5集成调用

Junit4只是简单的使用的示例,是需要结合Junit4的@Rule的注解使用,相对Junit5和TestNG的使用会更简洁些,下面就是以Junit5进行接口的Mock测试。

  1. 引入Junit5的依赖

    1
    2
    3
    4
    5
    6
    <dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>RELEASE</version>
    <scope>test</scope>
    </dependency>
  1. 编写代码,进行不同需求的Mock测试

    • 设置Mock响应规则
    • 设置响应简化规则
    • 重定向
    • 优先级规则
    • 服务端错误500
    • 场景的使用
    • 从文件获取响应内容
    • 消息录制
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
package com.wiremock.demo;

import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.stubbing.Scenario;
import io.restassured.RestAssured;
import org.junit.jupiter.api.*;

import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static io.restassured.RestAssured.given;

/**
* 在Junit5中WireMock的使用方法
*
* @author jingLv
* @date 2020/10/12
*/
public class WireMockForJunit5 {
// 创建WireMockServer的实例
static WireMockServer wireMockServer = new WireMockServer(8088, 8089);

@BeforeAll
static void setUp() {
// 启动WireMockServer
wireMockServer.start();
// 设置RestAssured
RestAssured.baseURI = "http://localhost:8088";
}

@AfterEach
public void teardown(TestInfo info) {
System.out.println("------------" + info.getDisplayName() + " finished!-------");
}

@Test
@DisplayName("设置基本监听规则")
void testMonitor01() {
// 设置Mock响应规则
wireMockServer.stubFor(get(urlEqualTo("/api/book/abc"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("test", "api")
.withBody("successful"))
);

// 请求已Mock响应规则接口
given()
.when()
.get("/api/book/abc")
.then()
.log().all();
}

/**
* 这是个一个简化写法
*/
@Test
@DisplayName("设置响应简化规则")
void testMonitor02() {
// 设置Mock响应规则
wireMockServer.stubFor(get(urlEqualTo("/api/book/abc"))
.willReturn(ok("successful"))
);

// 请求已Mock响应规则接口
given()
.when()
.get("/api/book/abc")
.then()
.log().all();
}

@Test
@DisplayName("重定向")
void testRedirect() {
wireMockServer.stubFor(post(urlEqualTo("/api/book/redirect"))
.willReturn(temporaryRedirect("/api/book/newPlace"))
);

given()
.when()
.post("/api/book/redirect")
.then()
.log().all();
}

@Test
@DisplayName("优先级规则的应用")
void testPriority() {
// 匹配所有的请求
wireMockServer.stubFor(any(anyUrl())
.atPriority(10)
.willReturn(notFound())
);

// 匹配符合路径的请求
wireMockServer.stubFor(get(urlMatching("/api/book/.*"))
.atPriority(5)
.willReturn(aResponse()
.withStatus(402)
.withBody("没有访问权限"))
);

// 匹配符合路径的请求
wireMockServer.stubFor(get(urlEqualTo("/api/book/test"))
.atPriority(1)
.willReturn(ok("测试地址"))
);

given()
.when()
.get("/test/none")
.then()
.log().status();

given()
.when()
.get("/api/book/none")
.then()
.log().all();

given()
.when()
.get("/api/book/test")
.then()
.log().all();
}

@Test
@DisplayName("服务端错误500")
void testServerError() {
wireMockServer.stubFor(post(urlEqualTo("/api/book/err"))
.willReturn(serverError())
);

given()
.when()
.post("/api/book/err")
.then()
.log().all();
}

@Test
@DisplayName("场景的使用方法")
void testScene() {
wireMockServer.stubFor(post(urlEqualTo("/rest/user"))
.willReturn(ok("{\"user\":\"admin\"}"))
);

wireMockServer.stubFor(post(urlEqualTo("/rest/user"))
.inScenario("get user")
.whenScenarioStateIs(Scenario.STARTED)
.willReturn(aResponse().withStatus(204))
.willSetStateTo("deleted")
);

wireMockServer.stubFor(post(urlEqualTo("/rest/user"))
.inScenario("get user")
.whenScenarioStateIs("deleted")
.willReturn(notFound())
);

given()
.when()
.post("/rest/user")
.then()
.log().all();

given()
.when()
.delete("/rest/user")
.then()
.log().all();

given()
.when()
.post("/rest/user")
.then()
.log().all();
}

/**
* 从文件中返回消息响应内容
*/
@Test
@DisplayName("从文件获取响应内容")
void getFileBody() {
// filebody.json文件获取在resources/mock/__files目录下
wireMockServer.stubFor(get(urlEqualTo("/api/book/file"))
.willReturn(aResponse().withStatus(200).withBodyFile("filebody.json")));

// 请求接口
given()
.when()
.post("/api/book/file")
.then()
.statusCode(200)
.log().all();
}

/**
* WireMock消息录制
*/
@Test
@DisplayName("消息录制")
void testRecorder() {
// 设置https的请求地址
RestAssured.baseURI = "http://localhost:8089";
// https校验
RestAssured.useRelaxedHTTPSValidation();
// 启动录制
wireMockServer.startRecording("");

// 请求接口
given()
.when()
.post("/rest/user")
.then()
.statusCode(200)
.log().all();

// 关闭录制
wireMockServer.stopRecording();
}

@AfterAll
static void stopAll() {
// 关闭WireMockServer
wireMockServer.stop();
}
}