【问题标题】:Android Kotlin (Instrumented) test, asserting that the ImageButton has the right resource is not workingAndroid Kotlin (Instrumented) 测试,断言 ImageButton 有正确的资源不工作
【发布时间】:2019-12-22 21:57:51
【问题描述】:

我正在使用 Kotlin 开发一个 Android 应用程序。我正在为我的应用程序编写仪器测试。现在,我在测试 ImageButton 时遇到问题,因为它没有按预期工作。我想测试一个 ImageButton 视图在 Activity 打开时是否设置了正确的可绘制对象。

在我的活动 XML 布局文件中,我有一个带有以下代码的 ImageButton

<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" />

我编写了一个测试来断言图像按钮视图设置了正确的可绘制资源。以下是我的测试的实现。

@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))
    }
}

正如您在测试方法中看到的,我断言如果两个可绘制资源相等。当我运行测试时,测试总是失败。但它应该通过。我的代码中缺少什么以及如何修复它?

【问题讨论】:

  • 嗨 @Onik,Android 社​​区建议在 Stackoverflow 上使用该标签来解决 Android 相关问题。

标签: android android-testing android-imagebutton instrumented-test


【解决方案1】:

经过一番挣扎,我发现了问题。我发布解决方案以防其他人遇到同样的问题。问题是我没有使用正确的方法来检查两个可绘制对象是否相等。为了比较两个可绘制对象,我们必须比较它们的常量状态。我写了一个测试辅助函数来断言。

这是代码。

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

        Assert.assertTrue(drawable1ConstantState!!.equals(drawable2ConstantState))
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-05
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多