gpt4 book ai didi

java - 使用 JUNIT 测试运行 AsyncHttpClient

转载 作者:太空宇宙 更新时间:2023-11-04 13:24:34 25 4
gpt4 key购买 nike

我已经尝试运行以下 JUnit 测试。当我尝试打印 userHash 字符串时,我发现该字符串为空。这表明 httpclient 根本没有运行。我一直在关注这篇文章...

https://github.com/loopj/android-async-http/issues/173

这是我的类(class)。

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();
}
}

关于java - 使用 JUNIT 测试运行 AsyncHttpClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32793519/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com