LoaderTestCase.javaAPI DocAndroid 5.1 API3941Thu Mar 12 22:22:42 GMT 2015android.test


public class LoaderTestCase extends AndroidTestCase
A convenience class for testing {@link Loader}s. This test case provides a simple way to synchronously get the result from a Loader making it easy to assert that the Loader returns the expected result.

Fields Summary
Constructors Summary
Methods Summary
public TgetLoaderResultSynchronously(android.content.Loader loader)
Runs a Loader synchronously and returns the result of the load. The loader will be started, stopped, and destroyed by this method so it cannot be reused.

loader The loader to run synchronously
The result from the loader

        // Force class loading of AsyncTask on the main thread so that it's handlers are tied to
        // the main thread and responses from the worker thread get delivered on the main thread.
        // The tests are run on another thread, allowing them to block waiting on a response from
        // the code running on the main thread. The main thread can't block since the AysncTask
        // results come in via the event loop.
        new AsyncTask<Void, Void, Void>() {
            protected Void doInBackground(Void... args) {return null;}
            protected void onPostExecute(Void result) {}
        // The test thread blocks on this queue until the loader puts it's result in
        final ArrayBlockingQueue<T> queue = new ArrayBlockingQueue<T>(1);

        // This callback runs on the "main" thread and unblocks the test thread
        // when it puts the result into the blocking queue
        final OnLoadCompleteListener<T> listener = new OnLoadCompleteListener<T>() {
            public void onLoadComplete(Loader<T> completedLoader, T data) {
                // Shut the loader down

                // Store the result, unblocking the test thread

        // This handler runs on the "main" thread of the process since AsyncTask
        // is documented as needing to run on the main thread and many Loaders use
        // AsyncTask
        final Handler mainThreadHandler = new Handler(Looper.getMainLooper()) {
            public void handleMessage(Message msg) {
                loader.registerListener(0, listener);

        // Ask the main thread to start the loading process

        // Block on the queue waiting for the result of the load to be inserted
        T result;
        while (true) {
            try {
                result = queue.take();
            } catch (InterruptedException e) {
                throw new RuntimeException("waiting thread interrupted", e);

        return result;