我似乎已经跌入谷底,试图找到一种解决方案,该方案可以在我的Espresso测试中测试我的ImageButton是否具有特定的背景可绘制。但是我一直收到下面粘贴的错误。我已经提供了我认为相关的尽可能多的代码。
ImageButton
<ImageButton
android:id="@+id/image_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/ic_background_selector"
android:clickable="true"
android:src="@drawable/background" />
选择器
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/ic_background_error" android:state_activated="true" />
<item android:drawable="@drawable/ic_background_okay" android:state_activated="false" />
</selector>
自定义匹配项:
fun matchColor(expectedId: Int): Matcher<View> {
return object : BoundedMatcher<View, ImageButton>(ImageButton::class.java) {
override fun describeTo(description: Description?) {
description?.appendText("with text color: ")
description?.appendValue(expectedId)
}
override fun matchesSafely(item: ImageButton?): Boolean {
return item?.context?.resources?.getDrawable(expectedId)?.constantState == item?.drawable?.constantState
}
}
}
测试:
onView(withId(R.id.image_button)).check(matches(matchColor(R.drawable.ic_background_okay)))
我收到以下错误:
androidx.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: 'with text
color: <2131165331>' doesn't match the selected view. Expected: with text color:
<2131165331>Got: "AppCompatImageButton{id=2131296363, ...}
我建议您在更改图像更改时设置标签,并比较标签而不是图像本身。如果您没有设置标签并且不知道如何编写自定义匹配器,则可以通过活动找到imagebutton,并使用与应用程序中相同的逻辑来比较当前显示的图像。
@Test
fun test_image_button_compare_success() {
val activity = getActivityInstance();
val imageButton= activity?.findViewById((R.id.image_button)) as ImageButton
assertTrue(1==1) //Replace here with your control using image button
}
正在获取活动实例为taken from here
私人活动getActivityInstance(){final Activity [] currentActivity = {null};
getInstrumentation().runOnMainSync(new Runnable(){
public void run(){
Collection<Activity> resumedActivity = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED);
Iterator<Activity> it = resumedActivity.iterator();
currentActivity[0] = it.next();
}
});
return currentActivity[0];
}