title: How can I run code, that will call the class extended AsyncTask, under UI Thread in Unit testing class in Android Testing?
body: <p>First, let me give you the scenario:</p>
  
  <pre><code>interface TaskDone{
  
   void OnTaskDone(Object data)
  
  }
  
  
  public class DownloadImage extends AsyncTask&lt;String,Void, Bitmap&gt;{
  
      private TaskDone callback;
      public DownloadImage(TaskDone callback){this.callback=callback}
      @Override
      protected Bitmap doInBackground(String ...params){
  
          Bitmap image= null;
         // contact to server and download image
  
          return image;
  
      }
  
  
      @Override
      protected void onPostExecute(Bitmap result) {
  
              super.onPostExecute(result);
              if (result != null) {
                  callback.onTaskDone(result);
              }
          }
      }
  }
  </code></pre>
  
  <p>Now I want to do Unit test that the image is being downloaded. As it is mandatory that the DownloadImage class needs to be called from UI thread and I don't have any Activity class in my source packages. How can I write unit testing for DownloadImage class? I have done something like the following but it seems to me that runOnUIThread is not running.</p>
  
  <pre><code>class DownloadImageTest {
  
      @Before
       public void setUp() throws Exception {
  
              countDownLatch = new CountDownLatch(1);
  
      }
  
      public void test1_TaskDownload_should_download_a_lanscape_banner() throws Throwable {
  
          Context context = Mockito.mock(Context.class);
  
          Context contextSpy = PowerMockito.spy(context);
  
          Intent intent = new Intent(contextSpy, Activity.class);
  
          contextSpy.startActivity(intent);
  
          activity.startActivity(intent);
  
          activity.runOnUiThread(new Runnable() {
  
                  @Override
                  public void run() {
                      DownloadImage downloadImage = new DownloadImage(new TaskDone() {
                          @Override
                          public void onTaskDone(Object data) {            
                              rawImageLandscape = (Bitmap) data;
                              countDownLatch.countDown();
                          }
                      });
                      downloadImage.execute(URL);
                  }
          });
  
  
          try {
  
                countDownLatch.await(5, TimeUnit.SECONDS);
  
              } catch (InterruptedException e) {
  
                 e.printStackTrace();
              }
          }
  }
  </code></pre>
  
  <p>Any help would be greatly appreciated. Thanks for reading the question too.<code>enter code here</code></p>