Android单元测试:模拟上下文也返回循环程序

时间:2019-03-14 09:42:36

标签: java android unit-testing android-context android-looper

这是我的示例代码:
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);
    }
}

以上代码在NullPointerException的{​​{1}}行生成了final Looper looper = mContext.getMainLooper();
如何设置模拟上下文对象以避免此异常?

1 个答案:

答案 0 :(得分:0)

假设您正在使用Mockito,则可以向模拟对象添加模拟行为:

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);
    }
}