赞
踩
1、访问WireMock官网地址:http://wiremock.org/,并点击【Docs】,如下图:
2、弹出的窗口,依次点击【Running as a Standalone Process 】——>【downloaded the standalone JAR】,下载【wiremock-jre8-standalone-2.31.0.jar】包,放到磁盘指定目录下,如下图:
3、lz下载到C盘的一个文件夹中,如下图:
4、【Win+R】打开dos命令行,进入该目录,执行 【java -jar wiremock-jre8-standalone-2.31.0.jar --port 8888】命令,其中端口可以任意指定,启动wiremock服务,如下图:
1、springboot项目结构如下:
2、pom.xml文件引入wiremock依赖
<!-- 引入wiremock -->
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock</artifactId>
<version>2.27.2</version>
</dependency>
3、创建2个txt文件,用于返回JSON格式的数据,文件内容如下:
orderFile1文件内容
{
"id":1,
"number":20210914,
"name":"电子产品",
"price":"5000"
}
orderFile2文件内容
{
"id":2,
"number":20210915,
"name":"小米",
"price":"3000"
}
3、编写一个MockClient客户端来连接wiremock服务器,代码如下:
package com.xz.springsecuritydemo.wiremock; import java.io.IOException; import com.github.tomakehurst.wiremock.client.WireMock; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.springframework.core.io.ClassPathResource; /** * @description: * @author: xz */ public class MockClient { public static void main(String[] args) { WireMock.configureFor(8888);//指定端口 WireMock.removeAllMappings();//清空上一次的发布信息 try { mock("/order/1", "orderFile1"); mock("/order/2", "orderFile2"); } catch (IOException e) { e.printStackTrace(); } } private static void mock(String url, String file) throws IOException { //获取类路径下的资源 ClassPathResource resource = new ClassPathResource("response/wiremock/" + file + ".txt"); //将内容连接成字符串 String content = StringUtils.join(FileUtils.readLines(resource.getFile(), "UTF-8").toArray(), ""); //发送一个GET请求,并指定url为/order/1,返回结果为withBody指定的得json内容 WireMock.stubFor(WireMock.get(WireMock.urlEqualTo(url)) .willReturn(WireMock.aResponse().withBody(content).withStatus(200))); //发送一个Post请求,并指定url,返回结果为withBody指定的得json内容 //WireMock.stubFor(WireMock.post(WireMock.urlEqualTo(url)).willReturn(WireMock.aResponse().withBody(content).withStatus(200))); } }
4、运行mian函数,如下图:
5、浏览器分别访问并访问 http://localhost:8888//order/1和 http://localhost:8888//order/2地址,如下图:
6、通过使用WireMock伪造REST服务,可以快速模拟出我们想要的各种请求和指定的返回内内容,这样前端就可以根据你这套服务去开发。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。