如何在 android 测试中测试 SearchView

问题描述 投票:0回答:0

我在为使用 SearchView 实现的搜索栏编写 android 测试时遇到问题。这是测试代码:

@Test
    fun searchFriends_displaysFilteredResults() {
        // Launch the FriendsFragment.
        launchFragmentInContainer<FriendsFragment>(themeResId = R.style.Theme_Bootcamp)

        var searchText = "John Doe"
        Thread.sleep(1000)
        onView(withId(R.id.friends_search_bar)).perform(click())
        onView(withId(R.id.friends_search_bar))
            .perform(typeText("John Doe"), closeSoftKeyboard())





        // Check if the filtered result is displayed.
        onView(withText("John Doe")).check(matches(isDisplayed()))
    }

这是包含搜索视图的片段的 xml:

<androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/fragment_friends"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.appcompat.widget.SearchView
        android:id="@+id/friends_search_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Search for users..."
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/friends_list"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintTop_toBottomOf="@id/friends_search_bar"
        app:layout_constraintBottom_toBottomOf="parent"
        tools:listitem="@layout/item_friend" />
</androidx.constraintlayout.widget.ConstraintLayout>

我的问题是

onView(withId(R.id.friends_search_bar)).perform(click())
没有打开搜索栏(默认情况下是折叠的)因此typeText(“John Doe”)不起作用。

它给出了以下错误: androidx.test.espresso.PerformException:在视图“view.getId() is <2131230996/com.epfl.drawyourpath:id/friends_search_bar>”上执行“type text(John Doe)”时出错。 Caused by: java.lang.RuntimeException: 由于目标视图不匹配以下一个或多个约束,将不会执行操作: (((view 具有有效可见性和 view.getGlobalVisibleRect() 返回非空矩形)) 和 (view.onCreateInputConnection() 不为空或可从类分配)) 目标视图:“SearchView{id=2131230996, res-name=friends_search_bar, visibility=VISIBLE, width=1080, height=126, has-focus=false, has-focusable=true, has-window-focus=true, is- clickable=false, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=false, is-selected=false, layout-params=androidx.constraintlayout.widget.ConstraintLayout$LayoutParams@ YYYYYY, tag=null, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=1}”

我尝试禁用所有动画,并使用 replaceText 而不是 typeText 但我得到了同样的错误。

android kotlin android-espresso searchview android-testing
© www.soinside.com 2019 - 2024. All rights reserved.