1

I am developing an Android application using Kotlin. I am writing instrumented tests for my application. Now, I am having a problem testing ImageButton because it is not working as expected. I want to test that an ImageButton view is set with the right drawable when the activity is opened.

In my activity XML layout file, I have an ImageButton with the following code

<ImageButton
        android:id="@+id/camera_image_btn_capture"
        android:adjustViewBounds="true"
        android:scaleType="centerInside"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        android:background="@null"
        android:src="@drawable/camera_capture"
        android:layout_width="85dp"
        android:layout_height="85dp" />

I have written a test to assert that the image button view is set with the right drawable resource. Following is the implementation of my test.

@RunWith(AndroidJUnit4::class)
@LargeTest
class CameraTest: TestBuilder()
{
    @get:Rule
    var cameraActivityRule: ActivityTestRule<CameraActivity> = ActivityTestRule<CameraActivity>(CameraActivity::class.java, true, false)

    @get:Rule
    var permissionRule: GrantPermissionRule = GrantPermissionRule.grant(android.Manifest.permission.CAMERA, android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE)

    @Test
    fun cameraCaptureImageButtonIsInitiallySetWithCaptureImage() {
        this.cameraActivityRule.launchActivity(null)
        val imageButtonCapture: ImageButton = this.cameraActivityRule.activity.findViewById<ImageButton>(R.id.camera_image_btn_capture)
        Assert.assertEquals(imageButtonCapture.drawable, this.cameraActivityRule.activity.getDrawable(R.drawable.camera_capture))
    }
}

As you can see in the test method, I am asserting that if two drawable resources are equal. When I run the test, the test always fails. But it is supposed to pass. What is missing in my code and how can I fix it?

Wai Yan Hein
  • 13,651
  • 35
  • 180
  • 372

1 Answers1

0

After struggling a bit, I found the issue. I am posting the solution in case anyone else is having the same issue. The problem was that I was not using the right way to check if two drawable objects are equal. To compare two drawable objects, we have to compare the constant states of them instead. I wrote a test helper function to assert that.

This is the code.

fun assertDrawablesEqual(drawable1: Drawable, drawable2: Drawable) {
        var drawable1ConstantState: Drawable.ConstantState? = drawable1.constantState
        var drawable2ConstantState: Drawable.ConstantState? = drawable2.constantState

        Assert.assertTrue(drawable1ConstantState!!.equals(drawable2ConstantState))
    }
Wai Yan Hein
  • 13,651
  • 35
  • 180
  • 372