我在Android JUnit测试中使用MockWebServer库。我正在测试可以调用服务器的SDK。因此,我正在使用MockWebServer
覆盖这些服务器URL,并捕获SDK发送的内容以对其进行断言。
我遇到的问题是,如果我尝试执行server.takeRequest()
并将其分配给新的RecordedRequest
变量,则测试会卡在第二个server.takeRequest()
上,有时甚至卡在第一个server.takeRequest()
上-如果我在模拟器上运行它它卡在第一个server.takeRequest()
方法上,但是如果我在物理Android设备上运行它,它将卡住在第二个MockWebServer
方法上。
public void testSomething() {
final MockWebServer server = new MockWebServer();
try {
server.play();
server.enqueue(new MockResponse().setBody("")
.setResponseCode(HttpURLConnection.HTTP_INTERNAL_ERROR));
server.enqueue(new MockResponse().setBody("")
.setResponseCode(HttpURLConnection.HTTP_OK));
server.enqueue(new MockResponse().setBody("")
.setResponseCode(HttpURLConnection.HTTP_OK));
URL url = server.getUrl("/");
// This internal method overrides some of the hardcoded URLs
// within the SDK that I'm testing.
Util.overrideUrls(url.toString())
// Do some server calls via the SDK utilizing the mock server url.
RecordedRequest requestFor500 = server.takeRequest();
// Do some assertions with 'requestFor500'
// Do some more server calls via the SDK utilizing the mock server url.
/*
* This is the part where the JUnit test hangs or seems to go into
* an infinite loop and never recovers
*/
RecordedRequest requestAfter500Before200 = server.takeRequest();
} catch {
...
}
}
我是在做错什么,还是ojit_code是某种类型的错误?
最佳答案
将超时添加到MockWebServer,使其不会挂起
server.takeRequest(1,TimeUnit.SECONDS);