如何为JUnit测试模拟OkHttp响应

5

我正在使用okhttp向第三方API发出HTTP请求:

public @Nullable result Call3rdParty {
    OkHttpClient client = new OkHttpClient.Builder()
        .connectTimeout(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)
        .readTimeout(RW_TIMEOUT, TimeUnit.MILLISECONDS)
        .retryOnConnectionFailure(true)
        .build();
    

    Request request = new Request.Builder()
       .url(url)
       .build();
    Response response = client.newCall(request).execute();

    //Deserialize and do minor data manipulation...
}

我希望创建一个单元测试,并模拟响应。

  private MockWebServer server;

  @Before
  public void setUp() throws IOException {
    this.server = new MockWebServer();
    this.server.start();
  }

  @After
  public void tearDown() throws IOException {
    this.server.shutdown();
  }

  @Test
  public void Test_SUCCESS() throws Exception {
    String json = readFileAsString(file);
    this.server.enqueue(new MockResponse().setResponseCode(200).setBody(json));
    //TODO: What to do here??
   }

在模拟响应被排队后,我需要做什么才能返回模拟响应并在我正在测试的方法的其余部分中使用它?

注:该问题涉及软件开发中的单元测试。

问题中的代码并不完整,并且已经有数百个在线教程等进行了回答。 - Yuri Schimke
@YuriSchimke请在此处提及其中一个以供参考。 - Asad Shakeel
一个随机的问题,很难知道最好的方法是什么,因为有很多不同的实现方式或测试目标。https://medium.com/android-news/unit-test-api-calls-with-mockwebserver-d4fab11de847 - Yuri Schimke
1个回答

1
这个项目文档涵盖了这个。

https://github.com/square/okhttp/tree/master/mockwebserver

  // Ask the server for its URL. You'll need this to make HTTP requests.
  HttpUrl url = server.url("/myendpoint");

  // Call your client code here, passing the server location to it
  response = Call3rdParty(url)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接