在仪器化的单元测试中,哪种方法更好地访问上下文?

问题描述

在仪器化的单元测试中,更建议以下哪一项访问Context:使用ApplicationProviderInstrumentationRegistry

val context: Context = ApplicationProvider.getApplicationContext()
import androidx.test.platform.app.InstrumentationRegistry

val context: Context = InstrumentationRegistry.getInstrumentation().targetContext

我知道androidx.test.InstrumentationRegistry已过时,但androidx.test.platform.app.InstrumentationRegistry却已过时。

解决方法

您可以根据您的SDK版本使用androidx.test.platform.app.InstrumentationRegistry或android.support.test.InstrumentationRegistry并通过以下方式获取上下文

上下文上下文= InstrumentationRegistry.getInstrumentation()。getTargetContext();