Android 测试中的模拟 Api 响应

El *_*ano 5 android robolectric android-testing

我正在寻找一种在 android 测试中模拟 api 响应的方法。

我已经读过机器人电可以用于此,但我真的很感激这方面的任何建议。

El *_*ano 4

在网上浏览了一下之后,我发现MockWebServer就是我正在寻找的东西。

用于测试 HTTP 客户端的可编写脚本的 Web 服务器。该库可以轻松测试您的应用程序在进行 HTTP 和 HTTPS 调用时是否执行正确的操作。它允许您指定要返回的响应,然后验证请求是否按预期发出。

要进行设置,只需将以下内容添加到您的build.gradle文件中。

androidTestCompile 'com.google.mockwebserver:mockwebserver:20130706'
Run Code Online (Sandbox Code Playgroud)

这是一个取自他们的 GitHub 页面的简单示例。

public void test() throws Exception {
    // Create a MockWebServer. These are lean enough that you can create a new
    // instance for every unit test.
    MockWebServer server = new MockWebServer();

    // Schedule some responses.
    server.enqueue(new MockResponse().setBody("hello, world!"));

    // Start the server.
    server.play();

    // Ask the server for its URL. You'll need this to make HTTP requests.
    URL baseUrl = server.getUrl("/v1/chat/");

    // Exercise your application code, which should make those HTTP requests.
    // Responses are returned in the same order that they are enqueued.
    Chat chat = new Chat(baseUrl);

    chat.loadMore();
    assertEquals("hello, world!", chat.messages());

    // Shut down the server. Instances cannot be reused.
    server.shutdown();
  }
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。