Search code examples
javaandroidmockitopowermockito

How can I use Mockito's verify on code running in Looper.getMainLooper?


Given this block of code:

    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            _view.displaySomething();
        }
    });

I want to call Mockito's verify(_view).displaySomething() in my unit test, but I receive the following error:

java.lang.RuntimeException: Method getMainLooper in android.os.Looper not mocked.

Can someone point me to what I could do to achieve this without error?


Solution

  • That is common problem with testing Android-related classes, they don't have default implementations when running pure JUnit test.

    You have two possibilities:

    • seperate your logic from Android framework - then you can test everything flawlessly. It is always a good idea to separate framework from your logic. This is also one of the main purposes of all popular architectures, be it MVP, MVVM or MVI
    • run your test as Android Instrumented Test (with Android JUnit runner) - then classes from Android sdk simply work as expected. Drawback - you must use device or emulator and your tests are slower.