如何在Android中进行HTTP请求的单元测试

5

我曾使用过库Robolectric,另一个可能的框架是Android的Http客户端http://loopj.com/android-async-http/

static AsyncHttpClient client = new AsyncHttpClient();

public static void getData (final ServerCallback callback) {

    client.get("http://httpbin.org/get", new AsyncHttpResponseHandler() {

        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            callback.onSuccess(statusCode, new String(responseBody));
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            callback.onFailure(statusCode, new String(responseBody));
        }

    });
}

测试类:

@RunWith(RobolectricTestRunner.class)
public class ApiTest{

@Test
public void testgetData () {

}

}

接口

public interface ServerCallback {
    // Api detect connection
    void onSuccess(int statusCode, String response);
    void onFailure(int statusCode, String response);
}

你尝试过进行模拟(mock)吗? - abbath
我想测试onSuccess和onFailure函数。 - Roma Darvish
你找到了解决这个问题的方法吗? - Ezio
1个回答

5

Роман,

我会提供一个简要答案,以帮助你走上正确的方向。我个人喜欢使用square okhttp mockwebserver来测试http请求。如果您对其使用有疑问,请查看该项目的单元测试

针对您的特定情况,有几件事需要处理:

  • 您需要覆盖测试中使用的基本url
  • android-async-http库是异步的,但是为了运行一致的单元测试,您需要将请求/响应设置为同步

因此,按照您的示例,让我们如下设置您的测试客户端:

public class TestHttpClient {
    // package-local client that can be set in tests
    static AsyncHttpClient client = new AsyncHttpClient(); 
    // package-local baseUrl that can be set in tests
    static String baseUrl = "http://pastbin.org/";  

    public static void getData(final ServerCallback callback) {
        String url = baseUrl + "get";
        client.get(url, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                callback.onSuccess(statusCode, new String(responseBody));
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                callback.onFailure(statusCode, new String(responseBody));
            }
        });
    }
}

为了测试TestHttpClient,可以使用MockWebServer来启动一个服务器进行测试,并设置客户端向服务器发送请求:

@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE, sdk = Build.VERSION_CODES.LOLLIPOP)
public class TestHttpRequestTest {

    @Rule
    public MockWebServer mockWebServer = new MockWebServer();

    @Test
    public void getData_onSuccess_doesSomething() throws InterruptedException {
        // Here we are creating a mock ServerCallback.  We will use
        // this mock object to verify the callback is invoked
        ServerCallback callback = mock(ServerCallback.class);

        // To test the client, we need to send a request to the mock mockWebServer.
        // The MockWebServer spins up an actual backend to handle calls.  You MUST
        // setup the client to use the base Url of the mockWebServer instead of
        // the actual url e.g.: http://httpbin.org.
        TestHttpClient.baseUrl = mockWebServer.url("/").toString();

        // For testing, use a synchronous client so that we can get the response before
        // the test completes.
        TestHttpClient.client = new SyncHttpClient();

        // Set up the mockWebServer to return a MockResponse with
        // some data in the body. This data can be whatever you want... json, xml, etc.
        // The default response code is 200.
        mockWebServer.enqueue(new MockResponse().setBody("success"));
        // To simulate an error
        // mockWebServer.enqueue(new MockResponse().setResponseCode(500).setBody("error"));

        TestHttpClient.getData(callback); // calling the method under test

        verify(callback).onSuccess(200, "success"); // using verify of mockito
    }
}

注意事项:

  • async http client 库需要一些 Android 系统组件才能正常工作,因此您必须使用 @RunWith(...) 注释。
  • MockWebServer 需要在 Robolectric 中使用时将 sdk 设置为 v21 或更高版本的 @Config(sdk = 21)

要在项目中包含 mockwebserver & mockito,请将以下内容添加到 build.gradle 中:

dependencies {
        testCompile 'com.squareup.okhttp3:mockwebserver:3.2.0'
        testCompile 'org.mockito:mockito-core:1.10.19'
    }

愉快的测试!!!


感谢您的帮助...错误:无法解析方法'mock(java.long.Class)'和无法解析方法'verify(java.long.Class)'。 - Roma Darvish
mockverify是来自mockito库的方法。我更新了答案中的附加依赖项,包括mockito。 - abest

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