1 // Copyright 2015 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 package org.chromium.base.task.test; 6 7 import static org.junit.Assert.fail; 8 9 import org.robolectric.annotation.Implementation; 10 import org.robolectric.annotation.Implements; 11 import org.robolectric.shadows.ShadowApplication; 12 13 import org.chromium.base.task.AsyncTask; 14 15 import java.util.concurrent.Callable; 16 import java.util.concurrent.Executor; 17 import java.util.concurrent.ExecutorService; 18 import java.util.concurrent.Executors; 19 20 /** 21 * Executes async tasks on a background thread and waits on the result on the main thread. 22 * This is useful for users of AsyncTask on Roboelectric who check if the code is actually being 23 * run on a background thread (i.e. through the use of {@link ThreadUtils#runningOnUiThread()}). 24 * @param <Result> type for reporting result 25 */ 26 @Implements(AsyncTask.class) 27 public class BackgroundShadowAsyncTask<Result> extends ShadowAsyncTask<Result> { 28 private static final ExecutorService sExecutorService = Executors.newSingleThreadExecutor(); 29 30 @Override 31 @Implementation executeOnExecutor(Executor e)32 public final AsyncTask<Result> executeOnExecutor(Executor e) { 33 try { 34 return sExecutorService 35 .submit( 36 new Callable<AsyncTask<Result>>() { 37 @Override 38 public AsyncTask<Result> call() { 39 return BackgroundShadowAsyncTask.super.executeInRobolectric(); 40 } 41 }) 42 .get(); 43 } catch (Exception ex) { 44 fail(ex.getMessage()); 45 return null; 46 } 47 } 48 49 @Override 50 @Implementation 51 public final Result get() { 52 try { 53 runBackgroundTasks(); 54 return BackgroundShadowAsyncTask.super.get(); 55 } catch (Exception e) { 56 return null; 57 } 58 } 59 60 public static void runBackgroundTasks() throws Exception { 61 sExecutorService 62 .submit( 63 new Runnable() { 64 @Override 65 public void run() { 66 ShadowApplication.runBackgroundTasks(); 67 } 68 }) 69 .get(); 70 } 71 } 72