我正在使用 Kotlin 开发 Android 应用程序。我正在为我的应用程序编写仪器测试。现在,我在测试 ImageButton 时遇到问题,因为它没有按预期工作。我想测试打开 Activity 时是否使用正确的可绘制对象设置了 ImageButton View 。
在我的 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" />
我已经编写了一个测试来断言图像按钮 View 设置了正确的可绘制资源。以下是我的测试的实现。
@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))
}
}
如您在测试方法中所见,我断言两个可绘制资源是否相等。当我运行测试时,测试总是失败。但它应该会过去。我的代码中缺少什么,我该如何修复?
最佳答案
经过一番努力,我发现了问题所在。我正在发布解决方案,以防其他人遇到同样的问题。问题是我没有使用正确的方法来检查两个可绘制对象是否相等。要比较两个可绘制对象,我们必须比较它们的常量状态。我写了一个测试辅助函数来断言。
这是代码。
fun assertDrawablesEqual(drawable1: Drawable, drawable2: Drawable) {
var drawable1ConstantState: Drawable.ConstantState? = drawable1.constantState
var drawable2ConstantState: Drawable.ConstantState? = drawable2.constantState
Assert.assertTrue(drawable1ConstantState!!.equals(drawable2ConstantState))
}
关于Android Kotlin (Instrumented) 测试,断言 ImageButton 具有正确的资源不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59448320/