lundi 30 novembre 2015

Android Unit testing with AsyncTask

Hey everyone just getting started with Android testing and I am trying to test an async task. Here is the async task code. I am following this SO post Android AsyncTask testing with Android Test Framework. The runTestOnUiThread is not found in AndroidTestCase however. If I understand this correctly if its not run on the ui thread then the test finishes before the async task completes? Any help is greatly appreciated !

public class BackendTest extends AndroidTestCase {

    private static MyApi myApiService = null;
    private Context context;


    public void testAsyncJoke () throws Throwable{
        // create  a signal to let us know when our task is done.
        final CountDownLatch signal = new CountDownLatch(1);

        final AsyncTask<Pair<Context, String>, Void, String> myTask = new AsyncTask<Pair<Context, String>, Void, String>() {

            @Override
            protected String doInBackground(Pair<Context, String>... params) {
                if(myApiService == null) {  // Only do this once
                    MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
                            .setRootUrl("http://ift.tt/1To3LcZ");
                    myApiService = builder.build();
                }

                context = params[0].first;
                String name = params[0].second;

                try {
                    return myApiService.sayHi(name).execute().getData();
                } catch (IOException e) {
                    return e.getMessage();
                }
            }

            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);
                signal.countDown();
            }
        };

        // Execute the async task on the UI thread! THIS IS KEY!
        runTestOnUiThread(new Runnable() {

            @Override
            public void run() {
                myTask.execute("Do something");
            }
        });

        signal.await(30, TimeUnit.SECONDS);

        // The task is done, and now you can assert some things!
        assertTrue("Happiness", true);
    }
}

Aucun commentaire:

Enregistrer un commentaire