在带有浓缩咖啡的底板上找不到视图



>我有一个Fragmant,其中包含一个有两个孩子的CoordinatorLayout:一个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:在层次结构中找不到视图 匹配:(id:kade.com.accio:id/random_poi,内容描述:是"随机兴趣点",具有父匹配:与id:kade.com.accio:id/design_bottom_sheet,并在屏幕上显示给用户)

那是因为我的按钮在底板上吗?为什么我找不到此视图?

首先你必须加载片段(否则没有片段要测试),所以有两种方法

1.) 实例化您的片段对象并使用片段管理器加载,例如

   @Before  // you can do it later 
    void setup(){
       fragment = ...    
       getActivity().getFragmentManager().beginTransaction().add(id,farment).commit()
 // or  activityTestRule.getActivity()
 //           .getSupportFragmentManager().beginTransaction()
   }

注意:如果您的视图不在屏幕外,则可以使用withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE)而不是isDisplayed()

最新更新