单元测试(unit testing),是指对软件中的最小可测试单元进行检查和验证。对于单元测试中单元的含义,一般来说,要根据实际情况去判定其具体含义。
对于开发者来说,单元测试(模块测试)是开发者编写的一小段代码,用于检验被测代码的一个很小的、很明确的功能是否正确。
AndroidStudio如何使用单元测试
新建一个项目,自动会在包名下创建一个ApplicationTest.java
创建一个被测试的类,代码如下:
package com.zhou.dell.dtest0408_unittest;
/**
* author:zh
* version:v1.0
* date: 2016/4/8
* description:计算
*/
public class Compute {
public int add (int a , int b ) {
return a + b ;
}
}
在ApplicationTest的同级目录下(当然你可以自己创建一个文件夹)创建一个类继承InstrumentationTestCase,注意不是Instrumentation,代码如下:
package com.zhou.dell.dtest0408_unittest;
import android.test.InstrumentationTestCase;
/**
* author:zh
* version:v1.0
* date: 2016/4/8
* description:
*/
public class ExampleTest extends InstrumentationTestCase {
public void test() throws Exception {
Compute c = new Compute();
int expected =4;
int reality = c.add(1,3);
assertEquals(expected, reality);
}
}
点击Run->Edit Configurations->点击左上角的“+”->Android Tests,之后会出现如下窗口
![](http://7xsstf.com2.z0.glb.clouddn.com/androidTest.bmp)
我的配置如下:
![](http://7xsstf.com2.z0.glb.clouddn.com/ASTest2.bmp)
点击 绿色的三角形 或者 shilft + F10(记得开虚拟机或者连接真机)
由于expected的值和reality的值相同,所以test通过,右下角就会有绿色的进度条,如下图:
![](http://7xsstf.com2.z0.glb.clouddn.com/ASTest4.bmp)
![](http://7xsstf.com2.z0.glb.clouddn.com/ASTest5.bmp)
注意
- 这个测试类不一定要和ApplicationTest同级,可以自己新建一个文件夹
- 测试类中的方法必须是以test开头,不然系统不会识别
- 测试类是继承InstrumentationTestCase
- 单元测试可以测试一些很小很小的功能点,比如一些工具类中的方法,数据库的操作等等。
网友评论