Search code examples
androidandroid-espressoui-testing

Android - Espresso How to test an view after clicked and moved to another Activity


I'm beginner of Espresso UI Testing. I have an issue, I have found solution but I'm not know how to do that correctly :((

Problem: I have 2 ImageView, when I click on once will change drawable of it and start an Activity. I want to check drawable after click does correct?

My code

// In Main Activity
val imageView1 = findViewById(R.id.iv_button1)
imageView1.setOnClickListener {
    imageView1.setImageDrawable(resources.getDrawable(R.drawable.image1))
    startActivity(Intent(applicationContext, OtherAcitivy1::class.java))
}
val imageView2 = findViewById(R.id.iv_button2)
imageView2.setOnClickListener {
    imageView2.setImageDrawable(resources.getDrawable(R.drawable.image2))
    startActivity(Intent(applicationContext, OtherAcitivy2::class.java))
}

// In Android Test Class
...After run activiy
@Test
fun checkClickImageView1() {
    onView(withId(R.id.iv_button1)).perform(click())

    // In here, I want to check the imageview has displayed drawable correctly
    onView(withId(R.id.iv_button1)).check(withDrawableMatcher(R.drawable.image1))
}

But, It throw an exception is could not found view with R.id.iv_button1.

I think, because I start OtherActivty2 on action click so it could not found view with that id from root view of OtherActivty2

Have any solution can help me check drawable of ImageView in this case?

Thanks so much.


Solution

  • I would use espresso intents

    This way you capture that your app is going to open the other activity and respond with a result. Then, as the activity you are has not changed you can check the drawable there.

    The code in your case should be something like:

    @Test
    fun checkClickImageView1() {
        val result = Instrumentation.ActivityResult(Activity.RESULT_OK, null)
        // Set up result stubbing when an intent sent to "OtherAcitivy2" is seen.
        intending(hasComponent(OtherAcitivy2::class.java.name)).respondWith(result)
        onView(withId(R.id.iv_button1)).perform(click())
    
        onView(withId(R.id.iv_button1)).check(withDrawableMatcher(R.drawable.image1))
    }
    

    don't forget to add the espresso-intents dependencies in your build.gradle file.