1、去官网下载并启动:
2、引入Pom依赖(主要是com.github.tomakehurst:wiremock):
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock</artifactId>
<version>2.5.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.1</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>25.1-jre</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.5</version>
</dependency>
3、编写客户端设置请求与响应(大量静态引用,可以添加到Eclipse的偏好设置中,然后在代码中静态引用能够简化代码,(Preferences中直接搜索faj即可)菜单Preferences->java->Edit->Content Assist->Favorites->New Type):
package wiremock;
import com.github.tomakehurst.wiremock.client.WireMock;
public class WireMockClient {
public static void main(String[] args) {
// TODO Auto-generated method stub
WireMock.configureFor(8090); //很多重载方法,本地启动的,只需要指定端口即可
WireMock.removeAllMappings(); //清除以前的配置并重新配置
WireMock.stubFor(
WireMock.get(WireMock.urlPathEqualTo("/order/1")).
willReturn(WireMock.aResponse().
withBody("{"id":1,"name":"cqu2010"}").withStatus(200))); //伪造测试桩
}
}
参数urlPathEqualTo和urlPathMatching表示URL严格匹配或正则匹配,withBody里面是json,后面可继续withStatus(状态码,200,400等整数),withHeaders等等,还有诸如statusMessage等,静态引用以后get要选wiremock的不要选spring的。
运行main方法后,服务器控制台输出:
Closest match:
{
"urlPath":"/order/1",
"method":"GET"
}
在main方法里写json不方便,可在resources下建txt文件并用apache的commons-io读取:
如在resources/file创建order.txt文件,内容:
{
"id": 1,
"type": "A"
}
代码:
package com.example.security.wiremock;
/**
* 静态引用
* FileUtils由commons-io:commons-io:2.6提供,StringUtils由commons-lang:commons-lang:2.5提供
*/
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.core.io.ClassPathResource;
import java.io.IOException;
public class WireMockClient {
public static void main(String[] args) throws IOException {
configureFor(8090);
removeAllMappings();
mock("/order/1", "order"); //这样可以在resources/file目录下建立多个txt文件,在这里配置多条这样的语句即可
}
public static void mock(String url, String fileName) throws IOException {
ClassPathResource resource = new ClassPathResource("/file/" + fileName + ".txt");
// String content = FileUtils.readFileToString(resource.getFile()); //建议废弃
String content = StringUtils.join(FileUtils.readLines(resource.getFile(), "UTF-8").toArray(), "
");
stubFor(get(urlPathEqualTo(url)).willReturn(aResponse().withBody(content).withStatus(200)));
}
}
其它高级用法诸如定义请求头,路径,请求参数,记录行为,记录请求过程等,参考官方文档。
4、测试: