目的,有三个人使用接口,安卓苹果和前端,这时候每个人伪造就会做三次,使用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.....................