我不明白为什么View.getContext()
在这种情况下返回null:
@Mock
Context mContext;
@Mock
SensorManager mSensorManager;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
// ...
@Test
public void initWithContext() throws Exception {
assertNotNull(mContext);
assertNotNull(mSensorManager);
when(mContext.getSystemService(Context.SENSOR_SERVICE)).thenReturn(mSensorManager);
ImageView imageView = new ImageView(mContext);
assertNotNull(imageView);
assertNotNull(imageView.getContext()); // Error because getContext() is null
}
View
构造函数的第一行:
public View(Context context) {
mContext = context;
方法getContext()
@ViewDebug.CapturedViewProperty
public final Context getContext() {
return mContext;
}
我没有嘲笑ImageView,为什么View.getContext()返回null呢?
修改
when(imageView.getContext()).thenReturn(mContext);
assertNotNull(imageView.getContext()); //Error, imageView.getContext() returns null
答案 0 :(得分:3)
如果这些是纯JVM单元测试(即在您的计算机的JVM上运行而不是在Android模拟器/设备上运行),那么您在任何Android类上都没有真正的方法实现。
你正在使用一个可模拟的jar,它只包含空类和删除了“final”的方法,所以你可以模拟它们,但它们并不像运行普通的Android那样真正起作用。
答案 1 :(得分:2)
我猜您的问题是@wojtek解释的问题,您正在运行本地单元测试,您可以模拟使用上下文来检索某些资源。
如果您需要在同一时间测试您的观看行为并模拟Android API,我建议您尝试Robolectric框架