在 Android UI 测试框架 Espresso 中,按下搜索视图(SearchView)中的操作按钮(例如搜索按钮)可以通过以下步骤实现。假设您已经设置了 Espresso 并编写了基本的测试用例。
确保您已经在项目中添加了 Espresso 依赖项:
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
androidTestImplementation 'androidx.test.espresso:espresso-intents:3.4.0'
androidTestImplementation 'androidx.test:runner:1.4.0'
androidTestImplementation 'androidx.test:rules:1.4.0'
以下是一个示例,展示如何在 Espresso 中按下 SearchView
中的搜索按钮。
在您的测试类中导入必要的 Espresso 类:
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.rule.ActivityTestRule;
import androidx.test.espresso.action.ViewActions;
import androidx.test.espresso.Espresso;
import androidx.test.espresso.matcher.ViewMatchers;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.action.ViewActions.typeText;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withContentDescription;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
设置 ActivityTestRule
以启动您的 Activity:
@RunWith(AndroidJUnit4.class)
public class SearchViewTest {
@Rule
public ActivityTestRule<MainActivity> activityRule =
new ActivityTestRule<>(MainActivity.class);
@Test
public void testSearchView() {
// 在这里编写测试代码
}
}
在 testSearchView
方法中编写测试代码:
@Test
public void testSearchView() {
// 假设 SearchView 的 ID 是 search_view
onView(withId(R.id.search_view))
.perform(click());
// 输入搜索关键字
onView(withId(R.id.search_src_text))
.perform(typeText("Espresso"));
// 按下搜索按钮
onView(withId(R.id.search_go_btn))
.perform(click());
// 验证搜索结果是否显示
onView(withId(R.id.search_results))
.check(matches(isDisplayed()));
}
SearchView
以展开它。onView(withId(R.id.search_view)) .perform(click());
SearchView
的输入框中输入搜索关键字。假设输入框的 ID 是 search_src_text
。onView(withId(R.id.search_src_text)) .perform(typeText("Espresso"));
SearchView
中的搜索按钮。假设搜索按钮的 ID 是 search_go_btn
。onView(withId(R.id.search_go_btn)) .perform(click());
search_results
。onView(withId(R.id.search_results)) .check(matches(isDisplayed()));
onView
和 withParent
等匹配器来定位视图。IdlingResource
或 Thread.sleep
(不推荐)来处理这种情况。领取专属 10元无门槛券
手把手带您无忧上云