13

我在我的 Android JUnit 测试中使用了 MockWebServer库。我正在测试一个调用服务器的 SDK。所以我MockWebServer用来覆盖这些服务器 URL 并捕获 SDK 发送的内容以对其进行断言。

我遇到的问题是,如果我尝试server.takeRequest()将其分配给一个新RecordedRequest变量,则测试会在第二个变量上挂起server.takeRequest(),有时甚至在第一个变量上——如果我在模拟器上运行它就会挂起第server.takeRequest()一种方法,但如果我在我的物理 Android 设备上运行它,它会冻结在第二种server.takeRequest()方法上。

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 {
    ...
  }
}

我做错了什么还是这是某种类型的错误MockWebServer

4

2 回答 2

3

为 MockWebServer 添加超时,使其不会挂起 server.takeRequest(1, TimeUnit.SECONDS);

于 2020-04-09T07:04:17.307 回答
1

MockWebServer 的调度队列似乎存在问题,在提供不是 200 或 302 的响应时,由于某种原因冻结。我通过提供自定义调度程序解决了这个问题:

MockWebServer server = ...;

final MockResponse response = new MockResponse().setResponseCode(401);

server.setDispatcher(new Dispatcher() {
    @Override
    public MockResponse dispatch(RecordedRequest request) 
        throws InterruptedException {
        return response; // this could have been more sophisticated
    }
});

使用 MockWebServer 2.0.0 测试

于 2014-09-24T10:50:45.493 回答