在 Android junit 测试用例中获取测试项目的上下文 [英] Get context of test project in Android junit test case
问题描述
有谁知道如何在Android junit 测试用例(扩展AndroidTestCase)中获取测试项目 的上下文.
Does anyone know how can you get the context of the Test project in Android junit test case (extends AndroidTestCase).
注意:该测试不是仪器测试.
Note: The test is NOT instrumentation test.
注意 2:我需要测试项目的上下文,而不是被测试的实际应用程序的上下文.
Note 2: I need the context of the test project, not the context of the actual application that is tested.
我需要它来从测试项目的资产中加载一些文件.
I need this to load some files from assets from the test project.
推荐答案
Android 测试支持库(当前为 androidx.test:runner:1.1.1
)提供了新方法.Kotlin 更新示例:
There's new approach with Android Testing Support Library (currently androidx.test:runner:1.1.1
). Kotlin updated example:
class ExampleInstrumentedTest {
lateinit var instrumentationContext: Context
@Before
fun setup() {
instrumentationContext = InstrumentationRegistry.getInstrumentation().context
}
@Test
fun someTest() {
TODO()
}
}
如果您还想运行应用上下文:
If you want also app context run:
InstrumentationRegistry.getInstrumentation().targetContext
完整运行示例:https://github.com/fada21/AndroidTestContextExample
看这里:getTargetContext() 和有什么区别getContext(在 InstrumentationRegistry 上)?
这篇关于在 Android junit 测试用例中获取测试项目的上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!