使用JUNIT测试运行AsyncHttpClient

时间:2015-09-26 04:08:34

标签: java android

我已经尝试过以下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();
        }





    }

1 个答案:

答案 0 :(得分:0)

您忘记了解决方案的CountdownLatch部分。这很重要,因为请求是异步的,因此您需要等到请求完成后才能查看结果。锁存器通过让调用线程等到响应处理程序调用{​​{1}}来完成此操作。

onFinish