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

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

相关推荐
tangweiguo0305198719 分钟前
Android 混合开发实战:统一 View 与 Compose 的浅色/深色主题方案
android
老狼孩1112228 分钟前
2025新版懒人精灵零基础及各板块核心系统视频教程-全分辨率免ROOT自动化开发
android·机器人·自动化·lua·脚本开发·懒人精灵·免root开发
打死不学Java代码1 小时前
PaginationInnerInterceptor使用(Mybatis-plus分页)
android·java·mybatis
IT乐手2 小时前
android 解决系统级应用 WebView 加载崩溃的问题
android
Kapaseker3 小时前
Kotlin泛型精解:类型世界的奇幻之旅
android·kotlin
顾林海3 小时前
深入探究 Android Native 代码的崩溃捕获机制
android·面试·性能优化
littleplayer3 小时前
iOS 单元测试与 UI 测试详解-DeepSeek
前端·单元测试·测试
爱分享的程序员3 小时前
前端跨端框架的开发以及IOS和安卓的开发流程和打包上架的详细流程
android·前端·ios
thigh_d4 小时前
uniapp 安卓离线本地打包,Android Studio生成apk包
android·uni-app·android studio
ACGkaka_5 小时前
Spring Boot实战(三十六)编写单元测试
spring boot·单元测试·log4j