Android AsyncTask testing with Android Test Framework

前端 未结 7 1353
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-27 09:42

I have a very simple AsyncTask implementation example and am having problem in testing it using Android JUnit framework.

It works just fine when I instantiate and e

相关标签:
7条回答
  • 2020-11-27 10:01

    The way to deal with this is to run any code that invokes an AsyncTask in runTestOnUiThread():

    public final void testExecute() {
        startActivity(_startIntent, null, null);
        runTestOnUiThread(new Runnable() {
            public void run() {
                Button btnStart = (Button) getActivity().findViewById(R.id.Button01);
                btnStart.performClick();
            }
        });
        assertNotNull(getActivity());
        // To wait for the AsyncTask to complete, you can safely call get() from the test thread
        getActivity()._myAsyncTask.get();
        assertTrue(asyncTaskRanCorrectly());
    }
    

    By default junit runs tests in a separate thread than the main application UI. AsyncTask's documentation says that the task instance and the call to execute() must be on the main UI thread; this is because AsyncTask depends on the main thread's Looper and MessageQueue for its internal handler to work properly.

    NOTE:

    I previously recommended using @UiThreadTest as a decorator on the test method to force the test to run on the main thread, but this isn't quite right for testing an AsyncTask because while your test method is running on the main thread no messages are processed on the main MessageQueue — including the messages the AsyncTask sends about its progress, causing your test to hang.

    0 讨论(0)
  • 2020-11-27 10:03

    If you don't mind executing the AsyncTask in the caller thread (should be fine in case of Unit testing), you can use an Executor in the current thread as described in https://stackoverflow.com/a/6583868/1266123

    public class CurrentThreadExecutor implements Executor {
        public void execute(Runnable r) {
            r.run();
        }
    }
    

    And then you run your AsyncTask in your unit test like this

    myAsyncTask.executeOnExecutor(new CurrentThreadExecutor(), testParam);
    

    This is only working for HoneyComb and higher.

    0 讨论(0)
  • 2020-11-27 10:04

    I met a similar problem while implementing some unit-test. I had to test some service which worked with Executors, and I needed to have my service callbacks sync-ed with the test methods from my ApplicationTestCase classes. Usually the test method itself finished before the callback would be accessed, so the data sent via the callbacks would not be tested. Tried applying the @UiThreadTest bust still didn't work.

    I found the following method, which worked, and I still use it. I simply use CountDownLatch signal objects to implement the wait-notify (you can use synchronized(lock){... lock.notify();}, however this results in ugly code) mechanism.

    public void testSomething(){
    final CountDownLatch signal = new CountDownLatch(1);
    Service.doSomething(new Callback() {
    
      @Override
      public void onResponse(){
        // test response data
        // assertEquals(..
        // assertTrue(..
        // etc
        signal.countDown();// notify the count down latch
      }
    
    });
    signal.await();// wait for callback
    }
    
    0 讨论(0)
  • 2020-11-27 10:05

    I wrote enough unitests for Android and just want to share how to do that.

    First off, here is helper class that responsible to wait and release waiter. Nothing special:

    SyncronizeTalker

    public class SyncronizeTalker {
        public void doWait(long l){
            synchronized(this){
                try {
                    this.wait(l);
                } catch(InterruptedException e) {
                }
            }
        }
    
    
    
        public void doNotify() {
            synchronized(this) {
                this.notify();
            }
        }
    
    
        public void doWait() {
            synchronized(this){
                try {
                    this.wait();
                } catch(InterruptedException e) {
                }
            }
        }
    }
    

    Next, lets create interface with one method that should be called from AsyncTask when work is done. Sure we also want to test our results:

    TestTaskItf

    public interface TestTaskItf {
        public void onDone(ArrayList<Integer> list); // dummy data
    }
    

    Next lets create some skeleton of our Task that we gonna test:

    public class SomeTask extends AsyncTask<Void, Void, SomeItem> {
    
       private ArrayList<Integer> data = new ArrayList<Integer>(); 
       private WmTestTaskItf mInter = null;// for tests only
    
       public WmBuildGroupsTask(Context context, WmTestTaskItf inter) {
            super();
            this.mContext = context;
            this.mInter = inter;        
        }
    
            @Override
        protected SomeItem doInBackground(Void... params) { /* .... job ... */}
    
            @Override
        protected void onPostExecute(SomeItem item) {
               // ....
    
           if(this.mInter != null){ // aka test mode
            this.mInter.onDone(data); // tell to unitest that we finished
            }
        }
    }
    

    At last - our unitest class:

    TestBuildGroupTask

    public class TestBuildGroupTask extends AndroidTestCase  implements WmTestTaskItf{
    
    
        private SyncronizeTalker async = null;
    
        public void setUP() throws Exception{
            super.setUp();
        }
    
        public void tearDown() throws Exception{
            super.tearDown();
        }
    
        public void test____Run(){
    
             mContext = getContext();
             assertNotNull(mContext);
    
            async = new SyncronizeTalker();
    
            WmTestTaskItf me = this;
            SomeTask task = new SomeTask(mContext, me);
            task.execute();
    
            async.doWait(); // <--- wait till "async.doNotify()" is called
        }
    
        @Override
        public void onDone(ArrayList<Integer> list) {
            assertNotNull(list);        
    
            // run other validations here
    
           async.doNotify(); // release "async.doWait()" (on this step the unitest is finished)
        }
    }
    

    That's all.

    Hope it will help to someone.

    0 讨论(0)
  • 2020-11-27 10:09

    Most of those solutions require a lot of code to be written for every test or to change your class structure. Which I find very difficult to use if you have many situations under test or many AsyncTasks on your project.

    There is a library which eases the process of testing AsyncTask. Example:

    @Test
      public void makeGETRequest(){
            ...
            myAsyncTaskInstance.execute(...);
            AsyncTaskTest.build(myAsyncTaskInstance).
                        run(new AsyncTest() {
                            @Override
                            public void test(Object result) {
                                Assert.assertEquals(200, (Integer)result);
                            }
                        });         
      }       
    }
    

    Basically, it runs your AsyncTask and test the result it returns after the postComplete() has been called.

    0 讨论(0)
  • 2020-11-27 10:10

    I found a lot of close answers but none of them put all the parts together correctly. So this is one correct implementation when using an android.os.AsyncTask in your JUnit tests cases.

     /**
     * This demonstrates how to test AsyncTasks in android JUnit. Below I used 
     * an in line implementation of a asyncTask, but in real life you would want
     * to replace that with some task in your application.
     * @throws Throwable 
     */
    public void testSomeAsynTask () throws Throwable {
        // create  a signal to let us know when our task is done.
        final CountDownLatch signal = new CountDownLatch(1);
    
        /* Just create an in line implementation of an asynctask. Note this 
         * would normally not be done, and is just here for completeness.
         * You would just use the task you want to unit test in your project. 
         */
        final AsyncTask<String, Void, String> myTask = new AsyncTask<String, Void, String>() {
    
            @Override
            protected String doInBackground(String... arg0) {
                //Do something meaningful.
                return "something happened!";
            }
    
            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);
    
                /* This is the key, normally you would use some type of listener
                 * to notify your activity that the async call was finished.
                 * 
                 * In your test method you would subscribe to that and signal
                 * from there instead.
                 */
                signal.countDown();
            }
        };
    
        // Execute the async task on the UI thread! THIS IS KEY!
        runTestOnUiThread(new Runnable() {
    
            @Override
            public void run() {
                myTask.execute("Do something");                
            }
        });       
    
        /* The testing thread will wait here until the UI thread releases it
         * above with the countDown() or 30 seconds passes and it times out.
         */        
        signal.await(30, TimeUnit.SECONDS);
    
        // The task is done, and now you can assert some things!
        assertTrue("Happiness", true);
    }
    
    0 讨论(0)
提交回复
热议问题