Volley的Android单元测试 [英] Android Unit test with Volley

查看:98
本文介绍了Volley的Android单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以为我的Android应用程序编写单元测试,在该应用程序中我将Volley用于网络请求.例如我想为登录功能编写一个单元测试,在该功能中,我将发布带有用户凭证的截击请求,并在响应中检查有效的用户对象.有人做过类似的事情吗?请提供示例或参考.

Is it possible to write a unit test for my android application where I use Volley for network request. For Eg. I want to write a unit test for a log in feature where in I post a volley request with users credentials and check for a valid user Object in the response. Has anyone done anything similar? Kindly provide examples or references.

这是我的登录方法:

    public void login() {
    try {
        JSONObject jsonRequest = new JSONObject();
        String emailString = email.getText().toString();
        jsonRequest.put("email", emailString);
        String passwordString = password.getText().toString();
        jsonRequest.put("password", passwordString);

        NetworkUtil.postLogin(new Listener<User>() {

            @Override
            public void onResponse(User response) {
                setUser(response);
                onUserSuccess();
            }
        }, new ErrorListener("postLogin") {

            @Override
            public void onErrorResponse(VolleyError error) {
                super.onErrorResponse(error);
                onUserError(error);
            }

        }, jsonRequest);
    } catch (Exception e) {
    }

我的postLogin方法类似于添加截击请求:

And my postLogin method would be something like adding a volley request:

    public static void postLogin(Listener<User> listener, ErrorListener errorListener,
        JSONObject jsonRequest) {
    VolleySingleton
            .getInstance()
            .getRequestQueue()
            .add(new GsonRequest<User>(getUrl("login"), "user_profile", User.class, jsonRequest, Method.POST,
                    listener, errorListener));
}

推荐答案

建议您使用CountDownLatch等待齐射响应,以便进行测试.否则,您的测试将在响应之前结束.

Suggest you using CountDownLatch to await the volley response so that you can do the test. Otherwise your test will end before the response.

在单元测试课中,使用:

In your unit test class using:

final CountDownLatch signal = new CountDownLatch(1);

/** your code here wait for response**/

signal.await();

/** your code here**/

在on response方法中,您应该添加 signal.countDown();

In the on response method you should add signal.countDown();

这是参考链接 https://github.com/loopj/android-async-http/issues/173

这篇关于Volley的Android单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆