gpt4 book ai didi

android - 在 JUnit 测试中,View.getContext() 在构造函数 View(context) 之后返回 null

转载 作者:太空狗 更新时间:2023-10-29 16:29:19 25 4
gpt4 key购买 nike

我不明白为什么 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;
}

我不是在 mock ImageView,为什么 View.getContext() 会返回 null?

编辑

when(imageView.getContext()).thenReturn(mContext);
assertNotNull(imageView.getContext()); //Error, imageView.getContext() returns null

最佳答案

如果这些是纯 JVM 单元测试(即在您计算机的 JVM 上运行,而不是在 Android 模拟器/设备上运行),那么您在任何 Android 类上都没有真正的方法实现。

您正在使用一个可模拟的 jar,它只包含删除了“final”的空类和方法,因此您可以模拟它们,但它们并不像运行普通 Android 时那样真正工作。

在这里查看更多信息:https://developer.android.com/training/testing/unit-testing/local-unit-tests.html#mocking-dependencies

关于android - 在 JUnit 测试中,View.getContext() 在构造函数 View(context) 之后返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42978302/

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