android测试主要有两种

1.本地测试(local test)

只在计算机中运行,这些测试运行在本地JVM中以减少执行时间。这种测试适合不需要android framework或者可以用模拟出的依赖来代替的测试。

2.设备测试(instrumentation test)

运行在android设备或者模拟器上的测试。这些测试需要使用到设备信息,如app的context。这种测试适合难以用mock代替的对象以及UI测试。

在最新的android studio(版本2.0)中,project已经分好了androidTest和test两个部分,前者用于设备测试,后者用于本地测试,从example中可见出区别。

以下详细讲两种测试的步骤:

本地测试

首先要配置好gradle的依赖信息

dependencies {// Required -- JUnit 4 frameworktestCompile 'junit:junit:4.12'// Optional -- Mockito frameworktestCompile 'org.mockito:mockito-core:1.10.19'
}

我们应该使用JUnit4来进行我们的测试开发。使用JUnit4,我们不再需要继承junit.framework.TestCase,我们也不再需要在方法名前以test作为前缀。

我们需要的是在测试方法前加上@Test的注释

我们可以用junit.Assert方法检车我们的返回值和期望值是否相同。

如果想让测试更加可读,我们可以使用Hamcrest matchers来进行匹配。

例如现在我们有一个User类

public class User{private String name;private int age;public User(String name, int age) {this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}
}

现在我们在测试中模拟一个用户,然后创建一个用户

将两个getAge方法进行对比

public class ExampleUnitTest {@MockUser mockUser;User user;@Beforepublic void setup(){MockitoAnnotations.initMocks(this);when(mockUser.getAge()).thenReturn(20);user = new User("haha",20);}@Testpublic void checkAge(){assertEquals(mockUser.getAge(),user.getAge());}
}

以下是android官方文档的sample:android文档传送门

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.*;
import static org.mockito.Mockito.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import android.content.SharedPreferences;@RunWith(MockitoJUnitRunner.class)
public class UnitTestSample {private static final String FAKE_STRING = "HELLO WORLD";@MockContext mMockContext;@Testpublic void readStringFromContext_LocalizedString() {// Given a mocked Context injected into the object under test...when(mMockContext.getString(R.string.hello_word)).thenReturn(FAKE_STRING);ClassUnderTest myObjectUnderTest = new ClassUnderTest(mMockContext);// ...when the string is returned from the object under test...String result = myObjectUnderTest.getHelloWorldString();// ...then the result should be the expected one.assertThat(result, is(FAKE_STRING));}
}

在官方例子中,就用了mock处理Context的问题
在左侧项目列表中右击类名,然后点击Run就可以运行该类,运行结束后就可以看到XX test passed,xx test failed的结果

mock的用法有很多,详细大家可以看《android开发进阶——从小工到专家》里面的介绍

给大家一个mockito官方文档的传送门:mock传送门

设备测试

设备测试运行在模拟器或者真机上,适合需要设备信息(如context)后者需要android framework组件(如Parcelable 或者 SharedPreference),可以减少mock的对象。
使设备测试还可以充分利用好android framework API,例如android testing support library。
和本地测试一样,我们要配置好测试库的依赖
dependencies {androidTestCompile 'com.android.support:support-annotations:23.0.1'androidTestCompile 'com.android.support.test:runner:0.4.1'androidTestCompile 'com.android.support.test:rules:0.4.1'// Optional -- Hamcrest libraryandroidTestCompile 'org.hamcrest:hamcrest-library:1.3'// Optional -- UI testing with EspressoandroidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1'// Optional -- UI testing with UI AutomatorandroidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.1.1'
}

这里的测试库包括了JUnit4和用于UI测试的Espresso和UI Automator(两者分别用于白盒测试和黑盒测试,选择自己需要的来用就好了)

Hamcrest是用于让断言(assert)函数更容易使用
为了让JUnit成为我们默认的测试运行器,我们需要在app 模块gradle文件中添加
android {defaultConfig {testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"}
}

例如这样:

<span style="font-family: Arial, Helvetica, sans-serif;">apply plugin: 'com.android.application'</span>
android {compileSdkVersion 22buildToolsVersion "22"defaultConfig {applicationId "com.my.awesome.app"minSdkVersion 10targetSdkVersion 22.0.1versionCode 1versionName "1.0"testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"}
}dependencies {// App's dependencies, including testcompile 'com.android.support:support-annotations:22.2.0'// Testing-only dependenciesandroidTestCompile 'com.android.support.test:runner:0.5'androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
}
创建测试类时要在前面加上@RunWith(AndroidJUnit4.class)
下面是范例
import android.os.Parcel;
import android.support.test.runner.AndroidJUnit4;
import android.util.Pair;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.List;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;@RunWith(AndroidJUnit4.class)
@SmallTest
public class LogHistoryAndroidUnitTest {public static final String TEST_STRING = "This is a string";public static final long TEST_LONG = 12345678L;private LogHistory mLogHistory;@Beforepublic void createLogHistory() {mLogHistory = new LogHistory();}@Testpublic void logHistory_ParcelableWriteRead() {// Set up the Parcelable object to send and receive.mLogHistory.addEntry(TEST_STRING, TEST_LONG);// Write the data.Parcel parcel = Parcel.obtain();mLogHistory.writeToParcel(parcel, mLogHistory.describeContents());// After you're done with writing, you need to reset the parcel for reading.parcel.setDataPosition(0);// Read the data.LogHistory createdFromParcel = LogHistory.CREATOR.createFromParcel(parcel);List<Pair<String, Long>> createdFromParcelData = createdFromParcel.getData();// Verify that the received data is correct.assertThat(createdFromParcelData.size(), is(1));assertThat(createdFromParcelData.get(0).first, is(TEST_STRING));assertThat(createdFromParcelData.get(0).second, is(TEST_LONG));}
}

我们还可以 创建一个以.suite结尾的包,在里面创建一个UnitTestSuite类,在类前加上@RunWith(Suite.class)@Suite.SuitClasses()

在SuiteClasses中列出测试用例

例子:
import com.example.android.testing.mysample.CalculatorAddParameterizedTest;
import com.example.android.testing.mysample.CalculatorInstrumentationTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;// Runs all unit tests.
@RunWith(Suite.class)
@Suite.SuiteClasses({CalculatorInstrumentationTest.class,CalculatorAddParameterizedTest.class})
public class UnitTestSuite {}

在后面我还会讲述UI测试库的用法,谢谢大家关注

android 测试开发概述相关推荐

  1. Android 培训课件编写--- 第1章 Android应用开发概述

    第1章 Android应用开发概述 随着Android系统的迅猛发展,它已经成为全球范围内具有广泛影响力的操作系统.Android系统已经不仅仅是一款手机的操作系统,它越来越广泛的被应用于平板电脑.可 ...

  2. Android测试原理概述(一)

    翻译来源:http://developer.android.com/tools/testing/testing_android.html 1.   Testing http://developer.a ...

  3. Android NFC开发概述

    NFC手机相比普通手机来说,有以下3个附加功能:  1.可以当成POS机来用,也就是"读取"模式   2.可以当成一张卡来刷,也就是NFC技术最核心的移动支付功能  3.可以像蓝牙 ...

  4. Android 底层开发概述(二)

    1. android底层开发 涉及到的知识范围和主要工作内容如下: 1. 知识集中在Linux kernel和驱动: 2. 工作主要是移植.bug fix: 3. 挑战性工作有:性能优化.功耗优化等. ...

  5. Android 智能手机开发概述

    Android SDK Android SDK 提供了在 Window/Linux/Mac 等平台上开发 Android 应用程序的相应的开发组件.它含有在 Android 平台上开发应用程序的工具集 ...

  6. android开发 nfc,Android NFC开发概述

    Near  Field Communication (NFC) 为一短距离无线通信技术,通常有效通讯距离为4厘米以内.NFC工作频率为13.65 兆赫兹,通信速率为106 kbit/秒到 848kbi ...

  7. Android 底层开发概述(一)

    1. Android移植 Linux 驱动程序工作在内核空间,android的HAL工作在用户空间,有了这两个部分的结合,就可以让庞大的android系统运行在特定的硬件平台上. 在具有了特定的硬件平 ...

  8. Android 底层开发概述(三)

    1. Android 内核 Android SDK通过HAL间接访问Linux驱动(一般的Linux系统都是由应用程序直接访问驱动).Android 并不能够使用从www.kernel.org下载的L ...

  9. Android 蓝牙开发——概述(一)

    一.蓝牙简介 蓝牙技术是一种无线数据和语音通信开放的全球规范,它是基于低成本的近距离无线连接,为固定和移动设备建立通信环境的一种特殊的近距离无线技术连接. 其中将1.x~3.0之间的版本称之为经典蓝牙 ...

  10. Android安卓|安卓概述、安卓开发、安卓入门、安卓架构

    Table of Contents Android 概述 什么是 Android? Android 开发优势 Android 的特性 Android 应用程序 Android 应用程序的类别 Andr ...

最新文章

  1. ASP.NET MVC 学习6、学习使用Code First Migrations功能,把Model的更新同步到DB中
  2. Chrome 开发者工具 live expression 的用法
  3. 现代软件工程 第六章 【敏捷流程】练习与讨论
  4. 比开源快30倍的自研SQL Parser设计与实践
  5. mysql 多点在 多边形,在MySQL中获取多点空间数据
  6. 一张图学会python3语法-一张图理清 Python3 所有知识点
  7. yolov3前向传播(二)-- yolov3相关模块的解析与实现(一)
  8. 程序员面试金典——1.2原串翻转
  9. Activity与Service之间交互并播放歌曲
  10. Android 11.0 12.0系统添加水印(仿安全模式水印)
  11. android 自定义地图标注,Android中调用高德地图的自定义标记视图
  12. zbbz的lisp_求CAD lisp 程序,选择一条或多条多段线,输出其上点的x,y,z坐标。
  13. 中国天气网城市代码爬取
  14. java学习练习预埋件配筋计算
  15. 几种前端h264播放器记录
  16. 西门子plc软件 linux,西门子PLC软件安装总结工程师们都在收藏
  17. wps excel 插入公式 整列
  18. 【滤波器】基于多种滤波器实现信号去噪含Matlab源码
  19. oracle 波浪号不识别,键盘波浪号“~”打不出,一直打成±,但安全模式却正常打出...
  20. 作业帮一面+二面+hr面

热门文章

  1. 视频云web播放器样式和组件自定义
  2. Sublime Text for Mac如何支持GBK编码
  3. ftp服务器FileZilla Server详细配置教程
  4. [WTL] 使用CImageList
  5. 基于matlab的信号频谱分析 开题报告,基于MATLAB的数字信号处理开题报告
  6. X-Scan 端口扫描工具下载和使用教程
  7. 良心安利三大游戏音效素材网站
  8. 使用RedisTemplate执行lua脚本
  9. 强力推荐!五款能让你成为Excel“高手”的Excel插件
  10. AdminLTE与php,如何使用Vue整合AdminLTE模板