Android AsyncTask testing with Android Test Framework

前端 未结 7 1351
爱一瞬间的悲伤
爱一瞬间的悲伤 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:23

    This can be used if you want to test the result from the doInBackground method. Override the onPostExecute method and perform the tests there. To wait for the AsyncTask to complete use CountDownLatch. The latch.await() waits till the countdown runs from 1 (which is set during initialization) to 0 (which is done by the countdown() method).

    @RunWith(AndroidJUnit4.class)
    public class EndpointsAsyncTaskTest {
    
        Context context;
    
        @Test
        public void testVerifyJoke() throws InterruptedException {
            assertTrue(true);
            final CountDownLatch latch = new CountDownLatch(1);
            context = InstrumentationRegistry.getContext();
            EndpointsAsyncTask testTask = new EndpointsAsyncTask() {
                @Override
                protected void onPostExecute(String result) {
                    assertNotNull(result);
                    if (result != null){
                        assertTrue(result.length() > 0);
                        latch.countDown();
                    }
                }
            };
            testTask.execute(context);
            latch.await();
        }
    
    0 讨论(0)
提交回复
热议问题