使用wiremock伪造restful服务

目的,有三个人使用接口,安卓苹果和前端,这时候每个人伪造就会做三次,使用wiremock一个服务就能解决。

访问官网,下载jar包,然后到该目录中去运行5的命令,在命令后边指定第6步的port。如下图

加入依赖:

<dependency>
	<groupId>com.github.tomakehurst</groupId>
	<artifactId>wiremock</artifactId>
</dependency>

题外话:设置favo来直接使用下边的静态方法。

创建类:

/**
 * 
 */
package com.imooc.wiremock;

import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.removeAllMappings;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;

import com.github.tomakehurst.wiremock.client.WireMock;

/**
 * @author 35-pxiaodong
 *
 */
public class MockServer {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		configureFor(8062);//指定端口
        removeAllMappings();//清除所有配置   
        stubFor(get(urlPathEqualTo("/order/1")).willReturn(aResponse().withBody("{\"id:\":1}").withStatus(200)));
	}

}

立即启动:命令窗口会有日志:

浏览器访问和查看响应:

进行重构:

/**
 * 
 */
package com.imooc.wiremock;

import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.removeAllMappings;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;

import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.core.io.ClassPathResource;

import com.github.tomakehurst.wiremock.client.WireMock;

/**
 * @author 35-pxiaodong
 *
 */
public class MockServer {

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		configureFor(8062);//指定端口
        removeAllMappings();//清除所有配置
        
        mock("/order/1","01");
	}

	private static void mock(String url, String fileName) throws Exception {
		ClassPathResource resource = new ClassPathResource("/mock/response/"+fileName+".txt");
        String content = StringUtils.join(FileUtils.readLines(resource.getFile(),"UTF-8").toArray(),"\n");
        stubFor(get(urlPathEqualTo(url)).willReturn(aResponse().withBody(content).withStatus(200)));
	}

}

可以直接添加服务:

更多wiremock精彩内容请阅读官网。。hia hia hia hia.....................

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值