gpt4 book ai didi

java - Android单元测试: Mock context that also returns a looper

转载 作者:太空宇宙 更新时间:2023-11-04 09:48:08 25 4
gpt4 key购买 nike

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

上面的代码在SomeClass中的final Looper Looper = mContext.getMainLooper();行生成了一个NullPointerException
如何设置模拟上下文对象以避免此异常?

最佳答案

假设您正在使用 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);
}
}

关于java - Android单元测试: Mock context that also returns a looper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55159243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com