我已经尝试运行以下JUnit测试。当我尝试打印出userHash字符串时,我发现该字符串为null。这表明httpclient根本没有运行。我一直在关注这个帖子...
https://github.com/loopj/android-async-http/issues/173
这是我的课。
public class ECApiManagerTests {
InstrumentationTestCase runnerHelper = new InstrumentationTestCase();
private final String userEmail = "removed";
private final String passWord = "removed";
String userHash;
@Test
public void testPOST()throws Throwable{
final AsyncHttpClient httpClient = new AsyncHttpClient();
runnerHelper.runTestOnUiThread(new Runnable() {
@Override
public void run() {
RequestParams params = new RequestParams();
params.put("email", userEmail);
params.put("password", passWord);
httpClient.post("https://edu.chat/api/login/", params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
//called when response code 200
userHash = new String(responseBody);
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
}
});
}
});
try {
System.out.println(userHash);
JSONObject obj = new JSONObject(userHash);
Assert.assertEquals("true", obj.getString("success"));
} catch (JSONException e) {
e.printStackTrace();
}
}
您忘记CountdownLatch
了解决方案的一部分。这很重要,因为请求是异步的,因此您需要等到请求完成后才能查看结果。闩锁通过让调用线程等待直到onFinish
从响应处理程序中调用来完成此操作。
public class ECApiManagerTests {
InstrumentationTestCase runnerHelper = new InstrumentationTestCase();
private final String userEmail = "removed";
private final String passWord = "removed";
String userHash;
@Test
public void testPOST()throws Throwable{
final AsyncHttpClient httpClient = new AsyncHttpClient();
final CountDownLatch signal = new CountDownLatch(1);
runnerHelper.runTestOnUiThread(new Runnable() {
@Override
public void run() {
RequestParams params = new RequestParams();
params.put("email", userEmail);
params.put("password", passWord);
httpClient.post("https://edu.chat/api/login/", params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
//called when response code 200
userHash = new String(responseBody);
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
}
@Override
public void onFinish() {
signal.countDown();
}
});
}
});
try {
signal.await(30, TimeUnit.SECONDS); // wait for callback
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
System.out.println(userHash);
JSONObject obj = new JSONObject(userHash);
Assert.assertEquals("true", obj.getString("success"));
} catch (JSONException e) {
e.printStackTrace();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句