use*_*337 3 android unit-testing android-volley android-instrumentation
是否可以为我的Android应用程序编写单元测试,我使用Volley进行网络请求.对于Eg.我想为登录功能编写单元测试,其中我发布了一个带有用户凭据的截击请求,并在响应中检查有效的用户对象.有没有人做过类似的事情?请提供示例或参考.
这是我的登录方法:
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) {
}
Run Code Online (Sandbox Code Playgroud)
我的postLogin方法就像添加一个截击请求:
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));
}
Run Code Online (Sandbox Code Playgroud)
小智 7
建议您使用CountDownLatch等待截击响应,以便您可以进行测试.否则,您的测试将在响应之前结束.
在您的单元测试类中使用:
final CountDownLatch signal = new CountDownLatch(1);
/** your code here wait for response**/
signal.await();
/** your code here**/
Run Code Online (Sandbox Code Playgroud)
在响应方法中,您应该添加
signal.countDown();
这里是参考链接https://github.com/loopj/android-async-http/issues/173
| 归档时间: |
|
| 查看次数: |
2788 次 |
| 最近记录: |