My app has an upload file functionality, which allows the user to choose a file (with a specific mime type) from the file picker and then the file will be shown in a list in the app. I want to test this with espresso, but so far, I faced many problems.
How I open the file explorer:
private fun openFileExplorer() {
val chooseFileIntent = Intent(Intent.ACTION_GET_CONTENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = mimeTypes.joinToString("|")
putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes)
}
startIntentForResult.launch(
Intent.createChooser(
chooseFileIntent,
getString(R.string.select_source)
)
)
}
How I listen to the activity result:
private val startIntentForResult =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
if (result.resultCode == Activity.RESULT_OK) {
val uri = result.data?.data
uri?.let { returnUri ->
// I get here
requireActivity().contentResolver.query(returnUri, null, null, null, null)
}?.use { cursor ->
// I cannot get here, since the file "doesn't exist" (name this THERE)
// I need this cursor for several reasons
createDocument(cursor, uri)
}
}
}
My Espresso test:
Intents.init()
intending(
expectingIntending
).respondWith(createImageGallerySetResultStub(resources))
onView(withId(R.id.my_button)).perform(click())
intended(expectingIntending)
Intents.release()
// is not displayed, since it doesn't have any items in it
onView(withId(R.id.my_list)).check(matches(isDisplayed()))
....
fun createImageGallerySetResultStub(resources: Resources): Instrumentation.ActivityResult {
val file = savePickedImage(resources)
val uri = Uri.fromFile(file)
val resultData = Intent()
resultData.setData(uri)
// if I use MediaStore.Images.Media.EXTERNAL_CONTENT_URI as uri, I can get THERE, but the folder is empty, I cannot use it...
return Instrumentation.ActivityResult(Activity.RESULT_OK, resultData)
}
fun savePickedImage(resources: Resources): File? {
val bm = BitmapFactory.decodeResource(resources, R.drawable.logo)
val dir = InstrumentationRegistry.getInstrumentation().targetContext.cacheDir
val file = File(dir.path, MY_IMAGE_NAME)
val outStream: FileOutputStream
return try {
outStream = FileOutputStream(file)
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream)
outStream.flush()
outStream.close()
file
} catch (e: FileNotFoundException) {
e.printStackTrace()
null
} catch (e: IOException) {
e.printStackTrace()
null
}
}
The file that I make with savePickedImage
gets created, I checked in the Device explorer.
But somehow during testing, it is not found and I cannot get further with my tests.
Any ideas?