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

时间:2017-03-23 14:01:52

标签: android junit mockito android-view android-testing

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

2 个答案:

答案 0 :(得分:3)

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

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

在此处查看更多内容:https://developer.android.com/training/testing/unit-testing/local-unit-tests.html#mocking-dependencies

答案 1 :(得分:2)

我猜您的问题是@wojtek解释的问题,您正在运行本地单元测试,您可以模拟使用上下文来检索某些资源。

如果您需要在同一时间测试您的观看行为并模拟Android API,我建议您尝试Robolectric框架