Android(安卓)单元测试之Espresso - Google官方UI测试框架
16lz
2021-12-04
Android 单元测试之Espresso - Google官方UI测试框架
Android 单元测试之JUnit和Mockito
Android 单元测试之Roboletric 环境配置
Android 单元测试之Roboletric的简单使用
Android 单元测试之Roboletric RxJava、Retrofit、访问真实网络、虚拟服务器
Android 单元测试之Espresso - Google官方UI测试框架
Espresso是Google官方推出的Instrumentation UI测试框架,在API支持方面有着天然的优势,在推出后很大程度上将替代Robotium。
Espresso官方文档
配置
android { ... defaultConfig { ... testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner' } packagingOptions { exclude 'LICENSE.txt' }}dependencies { ... androidTestCompile 'com.android.support.test:runner:0.5' androidTestCompile 'com.android.support.test:rules:0.5' androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2' androidTestCompile('com.android.support.test.espresso:espresso-contrib:2.2.2') { exclude module: 'support-annotations' exclude module: 'design' exclude module: 'recyclerview-v7' exclude module: 'support-v4' } androidTestCompile ('com.android.support.test.espresso:espresso-idling-resource:2.2.2') { exclude module: 'support-annotations' } compile 'com.android.support:design:24.1.1'}
构建时,可能会出现annotations 相关报错,加上下面的就好
android { configurations.all { resolutionStrategy.force 'com.android.support:support-annotations:23.0.1' }}
原因是目前 Espresso 对Android 部分代码只支持到 23.0.1 而我们项目中有些android版本为23.1.1,所以出现了报错
最简单的使用
新建布局
<?xml version="1.0" encoding="utf-8"?>
新建Activity
public class MainActivity extends AppCompatActivity { private TextView greetingView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setTitle(R.string.app_name); greetingView = (TextView) findViewById(R.id.greeting); } public void greet(View v) { greetingView.setText(R.string.hello); }}
新建单元测试
在androidTest中新建
@RunWith(AndroidJUnit4.class)public class MainActivityTest { @Rule public ActivityTestRule activityRele = new ActivityTestRule<>(MainActivity.class); @Test public void greet() { onView(withId(R.id.greeting)).check(matches(withText(""))); onView(withId(R.id.greet_button)).check(matches(withText(R.string.greet))).perform(click()); onView(withId(R.id.greeting)).check(matches(withText(R.string.hello))); } @Test public void toolbarTitle() { CharSequence title = InstrumentationRegistry.getTargetContext().getString(R.string.app_name); matchToolbarTitle(title); } private static ViewInteraction matchToolbarTitle(CharSequence title) { return onView(isAssignableFrom(Toolbar.class)) .check(matches(withToolbarTitle(is(title)))); } private static Matcher
然后,运行,发现测试通过
其他
源码Demo
更多相关文章
- Android(安卓)之 ProgressDialog用法介绍
- Android.Libraries
- Android(安卓)3.0 SDK 最新官方下载
- Android单元测试测试
- Android渗透测试Android渗透测试入门教程大学霸
- 最全的Android单元测试教程
- Android渗透测试Android渗透测试入门教程大学霸
- Android单元测试
- android 去掉标题栏 禁止横竖屏 保持全屏