我正在尝试从Square实现一个MockWebServer,我在代理后面。问题是每次我执行我的检测测试都会失败,因为我正在为我的MockWebServer做的每个请求获得407。
debug.level.titleD/OkHttp: <-- 407 Proxy Authentication Required http://localhost:12345/user/login (767ms)
当你看到我指向我的本地主机时,我不知道为什么我会得到这个!
这是我的MockWebServer实现!
public class MockedTestServer {
private final int PORT = 12345;
private final MockWebServer server;
private int lastResponseCode;
private String lastRequestPath;
/**
* Creates and starts a new server, with a non-default dispatcher
*
* @throws Exception
*/
public MockedTestServer() throws Exception {
server = new MockWebServer();
server.start(PORT);
setDispatcher();
}
private void setDispatcher() {
final Dispatcher dispatcher = new Dispatcher() {
@Override
public MockResponse dispatch(final RecordedRequest request) throws InterruptedException {
try {
final String requestPath = request.getPath();
final MockResponse response = new MockResponse().setResponseCode(200);
String filename;
// response for alerts
if (requestPath.equals(Constantes.ACTION_LOGIN)) {
filename = ConstantesJSON.LOGIN_OK;
} else {
// no response
lastResponseCode = 404;
return new MockResponse().setResponseCode(404);
}
lastResponseCode = 200;
response.setBody(RestServiceTestHelper.getStringFromFile(filename));
lastRequestPath = requestPath;
return response;
} catch (final Exception e) {
throw new InterruptedException(e.getMessage());
}
}
};
server.setDispatcher(dispatcher);
}
public String getLastRequestPath() {
return lastRequestPath;
}
public String getUrl() {
return server.url("/").toString();
}
public int getLastResponseCode() {
return lastResponseCode;
}
public void setDefaultDispatcher() {
server.setDispatcher(new QueueDispatcher());
}
public void enqueueResponse(final MockResponse response) {
server.enqueue(response);
}
public void shutdownServer() throws IOException {
server.shutdown();
}
当我执行仪器测试时,我的终点是“/".
只有当我在代理网络后面才会出现此问题,如果在我的移动设备中我切换到不在代理后面的另一个网络,则模拟服务器运行良好。知道我做错了吗?
编辑: 当我在代理后面时,调度员永远不会被称为
答案 0 :(得分:2)
好的,我最后才搞清楚....结果是我的okhttp3客户端指向真正的代理服务器,而不是localhost中的模拟Web服务器。我通过在测试Flavor时将代理添加到我的okhttp3客户端,然后将其添加到Retrofit2构建器来解决这个问题。代码看起来像这样。
if (BuildConfig.TEST_PROXY){
try {
InetSocketAddress sock = new InetSocketAddress(InetAddress.getByName("localhost"),12345);
builderOkhttpClient.proxy(new Proxy(Proxy.Type.HTTP, sock));
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
重要的是要注意,构建 InetSocketAddress 时的端口与模拟Web服务器端口相同。