4

I'm having trouble getting the main UI thread inside a robolectric(version 1.1) testcase. The application method I'm testing has the following check in it:

if (Thread.currentThread() != Looper.getMainLooper().getThread()) {
            throw new IllegalStateException(
                    "This method should be called from the Main UI Thread");
        }
    }

This check fails when invoked in the following way:

    @Test
public void maTest() {

    Runnable task = new Runnable() {

        @Override
        public void run() {

            adapter.testThreadPrecondition();

        }
    };

    new Handler(Looper.getMainLooper()).post(task);
}

Also tried "runOnUiThread", and got same check to fail. What is going on? different main loopers?

chris
  • 253
  • 2
  • 10
  • Also tried with an AsyncTask, but nothing inside "onPostExecute" seems to get called (or gets called but fails silently) task.execute(); Robolectric.getBackgroundScheduler().runOneTask(); Robolectric.getUiThreadScheduler().runOneTask(); – chris Jan 06 '14 at 20:18
  • ever found a solution to this? – theV0ID Jan 31 '14 at 20:46
  • sadly no, I removed the tests instead. – chris Jan 31 '14 at 22:07

1 Answers1

0

Put the code that checks whether the looper thread is the current thread into a method, say ValidateRunningOnLooperThread().

Then, in the unit test use a mocking framework, such as Mockito to mock that method to just return successfully.

Community
  • 1
  • 1
CJBS
  • 15,147
  • 6
  • 86
  • 135