Issue
I'm trying to access getExternalFilesDir(null)
from an Espresso test during the execution of a @BeforeClass
method to set up some app files before starting tests.
I'm trying to access it like this:
InstrumentationRegistry.getInstrumentation().context.getExternalFilesDir(null)
Environment.getExternalStorageState()
returns "mounted"
, yet getExternalFilesDir(null)
returns null in the above call, contrary to the documentation which states it would only return null if storage wasn't mounted.
Interestingly enough, InstrumentationRegistry.getInstrumentation().context.filesDir
does return a value, but it returns a non-existent folder which is under a test package instead of the app's actual package.
How can I access and write to app's scoped storage when setting up an Espresso test?
Solution
InstrumentationRegistry.getInstrumentation().context
gives you the context for the test APK.
InstrumentationRegistry.getInstrumentation().targetContext
gives you the context for the APK under test.
If the directory has not yet been created, getExternalFilesDir
might return null
the first time, so you may have to call it twice.
With targetSdk=30
on an API 30 emulator, this:
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())
}
}
Will print this on first install/run:
D/storage: null
D/storage: /storage/emulated/0/Android/data/com.example.test/files
and this on the second run:
D/storage: /storage/emulated/0/Android/data/com.example.test/files
D/storage: /storage/emulated/0/Android/data/com.example.test/files
More on behavior with targetSdk=30
:
https://developer.android.com/training/data-storage/use-cases#migrate-legacy-storage
Answered By - yogurtearl
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.