如何对HTTP请求Android进行单元测试

如何对HTTP请求Android进行单元测试,第1张

概述我使用了Robolectric库另一个可能的框架.适用于Androidhttp://loopj.com/android-async-http/的Http客户端staticAsyncHttpClientclient=newAsyncHttpClient();publicstaticvoidgetData(finalServerCallbackcallback){client.get("http://httpbin.org/get",

我使用了Robolectric库另一个可能的框架.适用于Android http://loopj.com/android-async-http/的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{@Testpublic voID testgetData () {}}

接口

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

解决方法:

Роман,

我将提供一个一般性的答案,以使您朝正确的方向前进.我测试http请求的首选方法是使用square okhttp mockwebserver.如果对它们的使用有疑问,请查看project’s unit tests.

在您的特定情况下,有几件事要解决:

>您需要覆盖测试中使用的基本网址
> 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    }}

笔记:

>异步http客户端库需要一些androID系统组件才能正常工作,因此您必须使用@RunWith(…)批注
> MockWebServer需要@Config(sdk = 21),且sdk设置为v21或更高版本才能与Robolectric一起使用.

包含模拟网络服务器&在您的项目中的模拟,将以下内容添加到build.gradle

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

测试愉快!!!

总结

以上是内存溢出为你收集整理的如何对HTTP请求Android进行单元测试全部内容,希望文章能够帮你解决如何对HTTP请求Android进行单元测试所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1120910.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-29
下一篇2022-05-29

发表评论

登录后才能评论

评论列表(0条)

    保存