| 注册
请输入搜索内容

热门搜索

Java Linux MySQL PHP JavaScript Hibernate jQuery Nginx
jopen
9年前发布

Android单元测试基础

最近项目组在尝试引入单元测试,于是对单元测试进行一些基本的了解。

基本概念

维基百科的定义:单元测试(又称为模块测试, Unit Testing)是针对程序模块(软件设计的最小单位)来进行正确性检验的测试工作。程序单元是应用的最小可测试部件。在过程化编程中,一个单元就是单个程序、函数、过程等;对于面向对象编程,最小单元就是方法,包括基类(超类)、抽象类、或者派生类(子类)中的方法。

《软件测试方法和技术》(朱少民 清华大学出版社 2005年7月第一版):单元测试是对软件基本组成单元的测试。单元测试的对象是软件设计的最小单位——模块。很多参考书中将单元测试的概念误导为一个具体函数或一个类的方法。一个最小的单元应该有明确的功能、性能定义、接口定义而且可以清晰地与其他单元区分开来。一个菜单、一个显示界面或者能够独立完成的具体功能都可以是一个单元。某种意义上单元的概念已经扩展为组件(component)

对单元测试的中单元的概念,其实大家的理解不是很一致。我更倾向于《软件测试方法和技术》的说法,单元测试的测试单元是具有明确的功能、性能定义、接口定义的模块。

作用

关于单元测试的作用其实也是广受争议。

http://stackoverflow.com/questions/67299/is-unit-testing-worth-the-effort

配置

官网例子

http://developer.android.com/training/testing/start/index.html

dependencies {

// Required — JUnit 4 framework

testCompile ‘junit:junit:4.12’

// Optional — Mockito framework

testCompile ‘org.mockito:mockito-core:1.10.19’

}

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 library

androidTestCompile ‘org.hamcrest:hamcrest-library:1.3’

// Optional — UI testing with Espresso

androidTestCompile ‘com.android.support.test.espresso:espresso-core:2.2.1’

// Optional — UI testing with UI Automator

androidTestCompile ‘com.android.support.test.uiautomator:uiautomator-v18:2.1.1’

}

testCompile与androidTestCompile区别

在dependencies中,大家可以看到testCompile和androidTestCompile,让人比较迷惑。实际上是测试使用的代码路径不同,testCompile用于src/test,测试Android环境无关的代码,androidTestCompile用于src/androidTest,测试与Android Api相关的部分。

以下为stackoverflow上的答案,相对清晰。

Simply testCompile is the configuration for unit tests (those located in src/test) and androidTestCompile is used for the test api (that located in src/androidTest). Since you are intending to write unit tests, you should use testCompile.

Update: The main distinction between the two is the test sourceset runs in a regular Java JVM, whereas the androidTest sourceset tests run on an Android device (or an emulator).

JUnit

junit已经成为java单元测试的最普及的框架。

Mockito

Robolectric

参考资料:

Android Traing:

http://developer.android.com/training/testing/start/index.html#config-local-tests

https://www.油Tube.com/watch?v=vdasFFfXKOY

美团:

http://tech.meituan.com/Android_unit_test.html
</div>

来自: http://coderrobin.com/2016/01/15/Android单元测试/

 本文由用户 jopen 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
 转载本站原创文章,请注明出处,并保留原始链接、图片水印。
 本站是一个以用户分享为主的开源技术平台,欢迎各类分享!
 本文地址:https://www.open-open.com/lib/view/open1452907590120.html
单元测试 安卓开发 Android开发 移动开发