I am developing an Android application using Kotlin. I am writing Integration Tests for my application using the Expresso framework. Now, I am struggling to mock the ClipData of the intent of the onActivityResult callback. I am mocking the intent using the expresso-intent of the Expresso framework.
Following is the implementation of my onActivityResult callback method.
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
Log.i(TAG, "Start handleGalleryActivityResult")
if (data?.clipData?.itemCount == null) {
return
}
if (data?.clipData?.itemCount as Int > 0) {
Log.i(TAG, "handleGalleryActivityResult: clipData count is greater than zero")
for (i in 0 until data?.clipData?.itemCount as Int) {
Log.i(TAG, "Processing index ${i}")
if (data?.clipData?.getItemAt(i)?.uri != null) {
val file: File = File(data?.clipData?.getItemAt(i)?.uri?.path)
Log.i(TAG, "Picked gallery file ${data?.clipData?.getItemAt(i)?.uri?.path}")
} else {
Log.i(TAG, "Picked gallery file at index ${i} is null")
}
}
}
}
As you can see in the onActivityResult callback method, I am retrieving the clipData of the intent.
I am writing a test mocking the returned intent as follows.
@Test fun filesAreUploadedToServerWhenPickedUpFromGallery() {
this.launchActivityWithIntent()
val resultData = Intent()
val result = Instrumentation.ActivityResult(Activity.RESULT_OK, resultData)
intending(IntentMatchers.hasAction(Intent.ACTION_PICK)).respondWith(result)
onView(withId(R.id.camera_image_btn_gallery)).perform(click())
//the rest of the code goes here
}
As you can see in my code, I am mocking the intent to be returned like this.
intending(IntentMatchers.hasAction(Intent.ACTION_PICK)).respondWith(result)
My question is how can I pass the Clip Data to the intent to mock it?
Create the ClipData
object as
Create
ClipDescription
andClipData.Item
objectval clipDescription = ClipDescription("Dummy", arrayOf(ClipDescription.MIMETYPE_TEXT_PLAIN)) val uri = Uri.parse("http://www.google.com"); val clipItem = ClipData.Item(uri)
Create
ClipData
object and set it on intent object as:val _clipData = ClipData(clipDescription, clipItem) resultData.clipData = _clipData
You can add more items using addItem as _clipData.addItem(clipItem)
. You can use other constructors and method of ClipDescription and ClipData.Item classes to add more data.
Alternately, You can create the actual mock objects and mock the corresponding methods for the same used objects, as per your mocking framework.