getExternalFilesDirnull在Espresso测试中返回null

问题描述

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

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

Environment.getExternalStorageState()返回"mounted",但是getExternalFilesDir(null)在上述调用中返回null,这与文档中的说明相反,该文档指出,只有在未装载存储的情况下,它才会返回null。

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

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

解决方法

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

如果尚未创建目录,getExternalFilesDir可能会第一次返回null因此您可能必须调用两次。

在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())
        }
    }

在第一次安装/运行时将其打印出来:

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...