问题描述
在仪器化的单元测试中,更建议以下哪一项访问Context
:使用ApplicationProvider
或InstrumentationRegistry
?
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();