【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版本不兼容,手机不支持时,单元测试都可能会执行失败

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

相关推荐
liang_jy5 小时前
Android 窗口容器树(一)—— 窗口和窗口容器树
android·源码
HUGu RGIN5 小时前
MySQL--》如何在MySQL中打造高效优化索引
android·mysql·adb
Joseph Cooper8 小时前
Linux/Android 跟踪技术:ftrace、TRACE_EVENT、atrace、systrace 与 perfetto 入门
android·linux·运维
空中海8 小时前
安卓逆向03. 动态调试、抓包分析与 Frida Hook
android
一起搞IT吧9 小时前
相机Camera日志实例分析之二十:相机Camx【照片后置4800/5000/6400万拍照】单帧流程日志详解
android·嵌入式硬件·数码相机·智能手机
jinanwuhuaguo10 小时前
(第三十三篇)五月的文明奠基:OpenClaw 2026.5.2版本的文明级解读
android·java·开发语言·人工智能·github·拓扑学·openclaw
千码君201612 小时前
Trae:一些关于flutter和 go前后端开发构建的分享
android·flutter·gradle·android-studio·trae·vibe code
重生之我是Java开发战士15 小时前
【MySQL】事务 & 用户与权限管理
android·数据库·mysql
中冕—霍格沃兹软件开发测试16 小时前
区块链交易最终一致性测试的核心挑战与实践框架
微服务·架构·单元测试·区块链·集成测试·旅游
怣疯knight17 小时前
Windows不安装 Android Studio如何打包安卓软件
android·windows·android studio