我有一个 Fragmant,它包含一个 CoordinatorLayout
和两个 child :一个 MapView
(Google Maps API) 和一个 RelativeLayout
,这是最后一个布局包含一些我想使用 Espresso
测试的按钮。
所以这是我的测试:
@Test
fun randomButtonTest() {
try {
Thread.sleep(2000)
} catch (e: InterruptedException) {
e.printStackTrace()
}
// Find the button and perform a click
val appCompatImageButton = onView(
allOf(withId(R.id.random_poi), withContentDescription("Random Point of Interest"),
withParent(withId(R.id.design_bottom_sheet)),
isDisplayed()))
appCompatImageButton.perform(click())
}
这是我的布局(为了可见性,我删除了所有与布局相关的参数):
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.gms.maps.MapView
android:id="@+id/mapView"/>
<RelativeLayout
android:id="@+id/design_bottom_sheet"
app:behavior_hideable="true"
app:layout_behavior="@string/bottom_sheet_behavior">
<ImageButton
android:id="@+id/up_arrow" />
<ImageButton
android:id="@+id/random_poi"
android:contentDescription="@string/random_poi"/>
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>
启动插桩测试时出现以下错误:
android.support.test.espresso.NoMatchingViewException: No views in hierarchy found matching: (with id: kade.com.accio:id/random_poi and with content description: is "Random Point of Interest" and has parent matching: with id: kade.com.accio:id/design_bottom_sheet and is displayed on the screen to the user)
那是因为我的按钮在底部工作表中吗?为什么我找不到这个 View ?
最佳答案
首先你必须加载 fragment (否则没有 fragment 可以测试)所以有两种方法
1.) 实例化您的 fragment 对象并使用 FragmentManager 加载
@Before // you can do it later
void setup(){
fragment = ...
getActivity().getFragmentManager().beginTransaction().add(id,farment).commit()
// or activityTestRule.getActivity()
// .getSupportFragmentManager().beginTransaction()
}
注意:如果您的 View 超出屏幕范围,则可以使用 withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE)
而不是 isDisplayed()
关于android - 使用 Espresso 在底页中找不到 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46693403/