进入wiremock官网,选择stand-alone,下载jar包
http://wiremock.org/docs/running-standalone/
运行该jar包,并设置端口号,如:
配置相关依赖:
<!-- wiremock 依赖 -->
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
注意:若没有引入httpclient和httpcore依赖,会抛出一下异常
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/http/HttpEntity
at com.github.tomakehurst.wiremock.client.WireMock.<init>(WireMock.java:70)
at com.github.tomakehurst.wiremock.client.WireMock.configureFor(WireMock.java:122)
at com.imooc.wiremock.MockServer.<clinit>(MockServer.java:19)
Caused by: java.lang.ClassNotFoundException: org.apache.http.HttpEntity
at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 3 more
在资源目录下,创建文件夹mock/response/0.1.txt
文件内容为:
{
"id":1,
"name":"lulu",
"age":25
}
编写代码:
public class MockServer {
static {
// 配置ip和端口
WireMock.configureFor("127.0.0.1", 8888);
// 清空以前的配置
WireMock.removeAllMappings();
}
public static void main(String[] args) throws IOException {
mock("/order/1", "01");
}
public static void mock(String url, String fileName) throws IOException {
ClassPathResource resource = new ClassPathResource("mock/response/" + fileName + ".txt");
// 处理回车
String content = StringUtils.join(FileUtils.readLines(resource.getFile(), "UTF-8"), "\n");
// get 表示 请求方法为 getMethod
WireMock.stubFor(WireMock.get(WireMock.urlEqualTo(url))
.willReturn(WireMock.aResponse().withBody(content).withStatus(200)));
}
}
运行主方法启动,然后进行请求 http://127.0.0.1:8888/order/1
返回结果: