getExternalFilesDir(null) returns 在 Espresso 测试中为 null

getExternalFilesDir(null) returns null in Espresso tests

我正在尝试在执行 @BeforeClass 方法期间从 Espresso 测试访问 getExternalFilesDir(null),以便在开始测试之前设置一些应用程序文件。

我正在尝试像这样访问它: InstrumentationRegistry.getInstrumentation().context.getExternalFilesDir(null)

Environment.getExternalStorageState() returns "mounted",但 getExternalFilesDir(null) returns 在上述调用中为 null,这与说明它只会 return 如果未安装存储则为 null。

有趣的是,InstrumentationRegistry.getInstrumentation().context.filesDir 确实 return 一个值,但它 return 是一个不存在的文件夹,它位于测试包下,而不是应用程序的实际包下。

设置 Espresso 测试时如何访问和写入应用程序的分区存储?

InstrumentationRegistry.getInstrumentation().context 为您提供测试 APK 的上下文。 InstrumentationRegistry.getInstrumentation().targetContext 为您提供被测 APK 的上下文。

如果目录还没有创建,getExternalFilesDir第一次可能returnnull所以你可能需要调用它两次。

在 API 30 模拟器上使用 targetSdk=30,这:

    companion object {
        @BeforeClass @JvmStatic
        fun beforeClass() {
            val targetContext = InstrumentationRegistry.getInstrumentation().targetContext
            Log.d("storage", targetContext.getExternalFilesDir(null).toString())
            Log.d("storage", targetContext.getExternalFilesDir(null).toString())
        }
    }

先打印这个 install/run:

D/storage: null
D/storage: /storage/emulated/0/Android/data/com.example.test/files

第二个 运行:

D/storage: /storage/emulated/0/Android/data/com.example.test/files
D/storage: /storage/emulated/0/Android/data/com.example.test/files

更多关于 targetSdk=30 的行为:
https://developer.android.com/training/data-storage/use-cases#migrate-legacy-storage