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

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

相关推荐
小蜜蜂嗡嗡2 分钟前
Android Studio flutter项目运行、打包时间太长
android·flutter·android studio
aqi008 分钟前
FFmpeg开发笔记(七十一)使用国产的QPlayer2实现双播放器观看视频
android·ffmpeg·音视频·流媒体
zhangphil2 小时前
Android理解onTrimMemory中ComponentCallbacks2的内存警戒水位线值
android
你过来啊你2 小时前
Android View的绘制原理详解
android
移动开发者1号5 小时前
使用 Android App Bundle 极致压缩应用体积
android·kotlin
移动开发者1号5 小时前
构建高可用线上性能监控体系:从原理到实战
android·kotlin
ii_best10 小时前
按键精灵支持安卓14、15系统,兼容64位环境开发辅助工具
android
美狐美颜sdk10 小时前
跨平台直播美颜SDK集成实录:Android/iOS如何适配贴纸功能
android·人工智能·ios·架构·音视频·美颜sdk·第三方美颜sdk
恋猫de小郭15 小时前
Meta 宣布加入 Kotlin 基金会,将为 Kotlin 和 Android 生态提供全新支持
android·开发语言·ios·kotlin
aqi0015 小时前
FFmpeg开发笔记(七十七)Android的开源音视频剪辑框架RxFFmpeg
android·ffmpeg·音视频·流媒体