0. 在wiremock的官网下载jar包, 并运行, http://wiremock.org/docs/running-standalone/
java -jar wiremock-standalone-2.26.3.jar
java配置方式
1. 引入wiremock的jar包,
2. 编辑代码
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;
/**
* @author zhailiang
*
*/
public class MockServer {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
configureFor(8062);
removeAllMappings();
mock("/order/1", "01"); //01,02为文件名, 放在classpath下的mock.response目录下
mock("/order/2", "02");
}
private static void mock(String url, String file) throws IOException {
ClassPathResource resource = new ClassPathResource("mock/response/" + file + ".txt");
String content = StringUtils.join(FileUtils.readLines(resource.getFile(), "UTF-8").toArray(), "\n");
stubFor(get(urlPathEqualTo(url)).willReturn(aResponse().withBody(content).withStatus(200)));
}
}
3, 编写返回的数据文件, 对应命名为01, 02
4, 举例01.txt的文件内容
5.启动main方法
6.浏览器上访问: localhost:8062/order/1, 返回01.txt的文件内容
json文件配置方式
wiremock server 在启动的时候, 会在jar包的同级目录下生成mappings和_files两个文件夹, 在mappings文件夹中创建json文件
一,直接在response中返回; 说明: mappings : 对应请求request位置 __files : 对应响应reponse位置 mappings中增减文件:get.json,内容入下: { "request": { "method": "GET", "url": "/api/mytest", "headers": { "Content-Type": { "equalTo": "application/json", "caseInsensitive": true } } }, "response": { "status": 200, "body": "{\"schemeName\":\"方案名称\",\"startTime\":\"2010.12.03\",\"endTime\":\"2010.12.03\"}" } } 执行步骤: 命令行: java -jar wiremock-standalone-2.14.0.jar -port 7777 浏览器: http://localhost:7777/api/mytest即可看到返回的json数据; 二,通过json文件方式返回: 1,__files中增加文件response.json,具体内容如下: { "equalToJson" : "{ \"name\": \"scheme\", \"id\": \"tester\", \"time\": \"2017-01-01\" }", "jsonCompareMode": "LENIENT" } 2,mappings中增加测试文件:test.json,内容如下: { "request": { "method": "GET", "urlPath": "/api" }, "response": { "status": 200, "bodyFileName": "response.json", "headers":{ "Content-Type": "application/json" } } } 执行步骤: 命令行: java -jar wiremock-standalone-2.14.0.jar -port 7777 浏览器: http://localhost:7777/api 即可看到__files中response.json中的json格式数据; 以上就是通过GET请求的两种返回json格式数据的方式;