行业知识
Android UI 测试工具- Espresso的配置及使用
2026-11-04 21:44:26
来源:互联网转载
-
介绍
本篇文章参考:Espresso谷歌官方介绍
Espresso是一个非常强大的Android UI测试框架,使用Espresso可模拟用户操作、检测数据编写简洁、漂亮、可靠的Android UI测试。
-
配置
添加Espresso依赖项
打开应用的build.gradle文件,注意不是顶级的build.gradle文件,是app/build.grdle。在依赖项中添加以下代码:需均使用androidx.test
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1' androidTestImplementation 'androidx.test:runner:1.5.2' androidTestImplementation 'androidx.test:rules:1.5.0'
设置插桩测试运行程序
将下行代码添加到同一build.gradle文件的android.defaultConfig中
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
添加第一个测试
一般会在程序的项目的src/androidTest/java/com.example.package/中创建测试,示例如下:
@RunWith(AndroidJUnit4.class) @LargeTest public class HelloEspressoTest { @Rule public ActivityScenarioRule activityRule = new ActivityScenarioRule(MainActivity.class); @Test public void testTextMatch() { //Text为Hello的控件是否目前显示在界面上 onView(withText("Hello")).check(matches(isDisplayed())); } }语法
Espresso API建议测试作者考虑用户在与应用互动时可能会执行的操作-找到界面元素并与之互动。同时,该框架会阻止直接访问应用的activity和视图,因为保留这些对象并在界面现成之外对其执行操作是导致测试不稳定的主要原因。因此,在Espresso API中看到getView()和getCurrentActivity()等方法,只需实现ViewAction和ViewAssertion就可以安全地对视图执行操作。
Espresso 的主要组件包括:
-
Espresso 用于与视图交互(通过 onView() 和 onData())的入口点。此外,还会公开不一定与任何视图相关联的 API,例如 pressBack()。
-
ViewMatchers 实现 Matcher
-
-
上一篇:Linux 内核获取函数size
下一篇:dns服务器怎么设置最好?