javaandroidunit-testingandroid-contextandroid-looper

Android Unit Tests : Mock context that also returns a looper


Here is my sample code :
SomeClass.java

public class SomeClass {
    public SomeClass(Context mContext) {
        final Looper looper = mContext.getMainLooper();
        Handler mHandler = new Handler(looper);
    }
}

SomeClassTest.java

public class SomeClassTest {
    private SomeClass mSomeClass;

    @Mock
    private Context mContext;

    @before
    public void setup(){
        mSomeClass = new SomeClass(mContext);
    }
}

The above code generates a NullPointerException at the line final Looper looper = mContext.getMainLooper(); in SomeClass.
How can I setup the mock context object to avoid this exception ?


Solution

  • Assuming you are using Mockito, you can add mock behavior to mock objects:

    public class SomeClassTest {
        private SomeClass mSomeClass;
        private Looper mLooper;
    
        @before
        public void setup(){
            mLooper = mock(Looper.class);
            Context ctx = mock(Context.class);
            when(ctx.getMainLooper()).thenReturn(mLooper);
            mSomeClass = new SomeClass(mContext);
        }
    }