主题:为没开发完成的接口做 mock,url 只能通过 localhost 连接到却不能用本地 ip 访问
目的:为一个不具有响应能力的接口,mock 一个响应,伪造测试接口的响应。
例如:
现在需要对 Aip:8088/services(运行 mock 程序在机器 A)发起请求,我需要在这个响应信息里面写入信息。
现在的问题是:
我想让别人远程调用, Aip 只能用 localhost ,修改为我本地 ip:192.168.46.12 地址之后接口响应链接超时。
pom.xml
<!--mock自定义测试模块-->
<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/mockwebserver -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>mockwebserver</artifactId>
<version>3.6.0</version>
<scope>test</scope>
</dependency>
testng 测试方法
@Test
public void testName() throws Exception {
/*
https://github.com/square/okhttp/tree/master/mockwebserver
https://www.jianshu.com/p/7dc3d12ac67f
*/
MockResponse mockResponse = new MockResponse();
mockResponse.setHeader("Content-Type", "application/json");
mockResponse.setHeader("Connection", "keep-alive");
mockResponse.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:48.0) Gecko/20100101 Firefox/48.0");
mockResponse.setHeader("Host", "192.168.46.12");
// mockResponse.setBody("{\"flag\":\"success\",\"message\":\"\"}");
// mockResponse.setBodyDelay(5, TimeUnit.SECONDS);
// server.enqueue(mockResponse);
// server.setDispatcher(new QueueDispatcherImpl());
server.setDispatcher(new QueueDispatcher() {
@Override
public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
switch (request.getMethod().toLowerCase()) {
case "post":
return new MockResponse().addHeader("aa", "1S").setBody("{\"flag\":\"success\",\"message\":\"\"}").setResponseCode(200);
case "get":
return new MockResponse().addHeader("aa", "2S").setBody("{\"flag\":\"faillure\",\"message\":\"\"}").setResponseCode(200);
default:
return new MockResponse().setResponseCode(400);
}
}
});
server.start(8088);
server.url("/services");
TimerOparation.sleep(3000);
}
现在的解决思路:改一个 start 函数的写法
server.start(InetAddress.getByName("192.168.46.12"),8088);//localhost 不可访问,ip可访问
// server.start(InetAddress.getByName("host"),8088);//localhost 可访问,ip不可访问
也不行