进入wiremock官网,选择stand-alone,下载jar包
http://wiremock.org/docs/running-standalone/
![](https://img-blog.csdnimg.cn/20200506104647467.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzAxNDIwNQ==,size_16,color_FFFFFF,t_70)
运行该jar包,并设置端口号,如:![](https://img-blog.csdnimg.cn/20200506104756667.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzAxNDIwNQ==,size_16,color_FFFFFF,t_70)
配置相关依赖:
<!-- 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
![](https://img-blog.csdnimg.cn/20200506105121374.png)
文件内容为:
{
"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
返回结果:
![](https://img-blog.csdnimg.cn/20200506105407668.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzAxNDIwNQ==,size_16,color_FFFFFF,t_70)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)