Android AsyncTask testing with Android Test Framework

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

提交回复
热议问题