【Android】JUnit和Espresso单元测试新手快速入门

引入依赖

dart 复制代码
	android {
	    defaultConfig {
	        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
	    }
	}
	
	dependencies {
	    testImplementation 'junit:junit:4.13.2'
	    androidTestImplementation 'androidx.test.ext:junit:1.1.0'
	    androidTestImplementation 'androidx.test:rules:1.1.0'
	    androidTestImplementation 'androidx.test:runner:1.1.0'
	    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
	}

Java代码测试

java 复制代码
	package com.android.myapplication;
	
	import org.junit.Test;
	
	import static org.junit.Assert.*;
	
	public class ExampleUnitTest {
	
	    @Test
	    public void addition_isCorrect() {
	        assertEquals(4, 2 + 2);
	    }
	}

点击被Test标注的方法,左侧的运行按钮,就可以执行测试任务

AndroidUI测试

java 复制代码
	package com.android.myapplication;
	
	import static androidx.test.espresso.Espresso.onView;
	import static androidx.test.espresso.action.ViewActions.click;
	import static androidx.test.espresso.matcher.ViewMatchers.withId;
	
	import android.content.Context;
	
	import androidx.test.platform.app.InstrumentationRegistry;
	import androidx.test.ext.junit.runners.AndroidJUnit4;
	import androidx.test.rule.ActivityTestRule;
	
	import org.junit.Assert;
	import org.junit.Rule;
	import org.junit.Test;
	import org.junit.runner.RunWith;
	
	@RunWith(AndroidJUnit4.class)
	public class ExampleInstrumentedTest {
	
	    @Rule
	    public ActivityTestRule<MainActivity> activityTestRule = new ActivityTestRule(MainActivity.class, true);
	
	    @Test
	    public void useAppContext() {
	        //验证包名是否正确
	        Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
	        Assert.assertEquals("com.android.myapplication", appContext.getPackageName());
	        //模拟点击事件
	        onView(withId(R.id.fab)).perform(click());
	        //启动Activity
	        activityTestRule.getActivity();
	    }
	}

点击被Test标注的方法,左侧的运行按钮,就可以执行测试任务

查看测试报告

测试任务执行完毕,会在app/build/reports目录下生成测试报告

报告会统计所有测试任务的执行结果,已经通过率

注意事项

Android单元测试,特别是Espresso框架,依赖于Gradle插件和SDK版本

Gradle插件版本不兼容,SDK版本不兼容,手机不支持时,单元测试都可能会执行失败

可能会遇到的意外比较多,如果不幸遇坑,需要靠自己去耐心尝试

相关推荐
Java猿_5 小时前
Spring Boot 集成 Sa-Token 实现登录认证与 RBAC 权限控制(实战)
android·spring boot·后端
Jerry8 小时前
Jetpack Compose Navigation
android
介一安全9 小时前
【Frida Android】实战篇17:Frida检测与绕过——基于inline hook的攻防实战
android·网络安全·逆向·安全性测试·frida
龙之叶10 小时前
Android如何通过adb命令push文件后在媒体库中显示
android·adb
Just_Paranoid11 小时前
【Settings】Android 设备信息相关参数的获取
android·5g·wifi·ip·sn·network
StarShip12 小时前
SystemServer类 与 system_server进程
android
画个太阳作晴天12 小时前
Android App 跟随系统自动切换白天/黑夜模式:车机项目实战经验分享
android·android studo
成都大菠萝12 小时前
2-2-2 快速掌握Kotlin-语言的接口默认实现
android
代码s贝多芬的音符12 小时前
android webview 打开相机 相册 图片上传。
android·webview·webview打开相机相册
游戏开发爱好者813 小时前
抓包工具有哪些?代理抓包、数据流抓包、拦截转发工具
android·ios·小程序·https·uni-app·iphone·webview