update time :2019-1-28 author:要你命三千又三千 type :学习笔记
文章目录
Android 测试总览
- 测试类别:测试金字塔,显示应用程序测试套件中应该包含的三类测试。
- 小测试是可以与生产系统隔离运行的单元测试。它们通常模拟每个主要组件,并且应该在您的机器上快速运行。(单元测试)
- 中等测试是在小测试和大测试之间进行的集成测试。它们集成了多个组件,并且可以在仿真器或真实设备上运行。(集成测试)
- 大型测试是通过完成UI工作流程运行的集成和UI测试。它们确保关键的最终用户任务在仿真器或真实设备上按预期工作。(UI测试)
各种测试在测试工作中所占的比例:70%小,20%中等,10%大
由于每个测试类别的不同特征,您应该包括测试金字塔的每个层的测试。虽然每个类别的测试比例可能因应用程序的使用情况而异,但我们通常建议在类别中进行以下划分: 70%小,20%中等,10%大。
背景知识的补充
Mock模式:模拟对象
在面向对象程序设计中,模拟对象(英语:mock object,也译作模仿对象)是以可控的方式模拟真实对象行为的假的对象,程序员通常创造模拟对象来测试其他对象的行为。
为什么要使用mock 模式
情形:在单元测试中,模拟对象可以模拟复杂的、真实的(非模拟)对象的行为, 如果真实的对象无法放入单元测试中。
- 真实对象的行为是不确定的(例如,当前的时间或当前的温度);
- 真实对象很难搭建起来; 真实对象的行为很难触发(例如,网络错误);
- 真实对象速度很慢(例如,一个完整的数据库,在测试之前可能需要初始化);
- 真实的对象是用户界面,或包括用户界面在内;
- 真实的对象使用了回调机制;
- 真实对象可能还不存在;
- 真实对象可能包含不能用作测试(而不是为实际工作)的信息和方法。
由操作步骤开始记录,一步一步理解Android开发的测试问题
Android 本地单元测试
-
如果您对Android框架有依赖关系,特别是那些与框架创建复杂交互的框架,那么最好使用Robolectric 包含框架依赖关系。
-
如果您的测试对Android框架的依赖性最小,或者测试仅依赖于您自己的对象,则可以使用像Mockito这样的模拟框架来包含模拟依赖项。
内在原理
使用Local测试,但测试过程又难免遇到调用系统API那怎么办?
其中一个方法就是mock objects,比如借助Mockito,另外一种方式就是使用Robolectric。Robolectric就是为解决这个问题而生的。它实现一套JVM能运行的Android代码,然后在unit test运行的时候去截取android相关的代码调用,然后转到他们的他们实现的Shadow代码去执行这个调用的过程。Mockito 更多的是实现了在本地的java代码的模拟。
仪器单元测试的使用
在开始之前,您应该添加Android测试api(它允许您快速构建和运行应用程序的测试代码。)Android测试的api 有:JUnit 4测试运行器(AndroidJUnitRunner)和用于功能UI测试的api (Espresso和UI Automator)
android 测试依赖的列表
dependencies {
// Core library
androidTestImplementation 'androidx.test:core:1.0.0'
// AndroidJUnitRunner and JUnit Rules
androidTestImplementation 'androidx.test:runner:1.1.0'
androidTestImplementation 'androidx.test:rules:1.1.0'
// Assertions
androidTestImplementation 'androidx.test.ext:junit:1.0.0'
androidTestImplementation 'androidx.test.ext:truth:1.0.0'
androidTestImplementation 'com.google.truth:truth:0.42'
// Espresso dependencies
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0'
androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.1.0'
androidTestImplementation 'androidx.test.espresso:espresso-intents:3.1.0'
androidTestImplementation 'androidx.test.espresso:espresso-accessibility:3.1.0'
androidTestImplementation 'androidx.test.espresso:espresso-web:3.1.0'
androidTestImplementation 'androidx.test.espresso.idling:idling-concurrent:3.1.0'
// The following Espresso dependency can be either "implementation"
// or "androidTestImplementation", depending on whether you want the
// dependency to appear on your APK's compile classpath or the test APK
// classpath.
androidTestImplementation 'androidx.test.espresso:espresso-idling-resource:3.1.0'
}
参考网址:https://developer.android.google.cn/training/testing/set-up-project#junit-based-libs
参考网址:Build instrumented unit tests(仪器单元测试的使用)