wiremock基本使用

进入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

返回结果:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值