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

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

相关推荐
Dingdangr2 小时前
Android中的Intent的作用
android
技术无疆2 小时前
快速开发与维护:探索 AndroidAnnotations
android·java·android studio·android-studio·androidx·代码注入
GEEKVIP2 小时前
Android 恢复挑战和解决方案:如何从 Android 设备恢复删除的文件
android·笔记·安全·macos·智能手机·电脑·笔记本电脑
Jouzzy9 小时前
【Android安全】Ubuntu 16.04安装GDB和GEF
android·ubuntu·gdb
极客先躯10 小时前
java和kotlin 可以同时运行吗
android·java·开发语言·kotlin·同时运行
Good_tea_h12 小时前
Android中的单例模式
android·单例模式
小码哥说测试16 小时前
软件测试技术之 GPU 单元测试是什么!
自动化测试·功能测试·测试工具·jmeter·单元测试·集成测试·postman
计算机源码社17 小时前
分享一个基于微信小程序的居家养老服务小程序 养老服务预约安卓app uniapp(源码、调试、LW、开题、PPT)
android·微信小程序·uni-app·毕业设计项目·毕业设计源码·计算机课程设计·计算机毕业设计开题
丶白泽17 小时前
重修设计模式-结构型-门面模式
android
晨春计19 小时前
【git】
android·linux·git