android - 在 Android junit 测试用例中获取测试项目的上下文

有谁知道如何在 Android junit 测试用例(扩展 AndroidTestCase)中获取 Test 项目 的上下文。

注意:该测试不是仪器测试。

注意 2:我需要测试项目的上下文,而不是被测试的实际应用程序的上下文。

我需要这个来从测试项目的 Assets 中加载一些文件。

最佳答案

Android 测试支持库(目前为 androidx.test:runner:1.1.1)提供了新方法。 Kotlin 更新示例:

class ExampleInstrumentedTest {

    lateinit var instrumentationContext: Context

    @Before
    fun setup() {
        instrumentationContext = InstrumentationRegistry.getInstrumentation().context
    }

    @Test
    fun someTest() {
        TODO()
    }
}

如果你还想运行应用上下文:

InstrumentationRegistry.getInstrumentation().targetContext

完整运行示例:https://github.com/fada21/AndroidTestContextExample

看这里:What's the difference between getTargetContext() and getContext (on InstrumentationRegistry)?

https://stackoverflow.com/questions/8605611/

相关文章:

android - 带有 Google Maps API v2 : mysterious black

android - 在 Android 中删除 SQLite 中的行

android - Html 列表标签在 android textview 中不起作用。我能做些什么

android - 为什么一个 Android Studio 项目中有两个 build.gradle

android - 使用按钮背景颜色为我的按钮添加波纹效果?

android - 是否可以在 xml 描述中旋转可绘制对象?

android - onActivityResult() & onResume()

android - 如何在 Activity 启动时在 ScrollView 中滚动到底部

android - 如何以编程方式在 View 中设置样式属性

android - 如何使用 HTML 5 创建一个安卓应用程序