Junit
尹琪
2011-01
目录
Junit 1
目录 2
什么是 JUnit 3
junit.framework包解析 6
android.test包的结构 8
junit.framework包中的TestListener接口 10
junit.runner包 11
AndroidTestRunner类 12
整个工程的结构图分析 12
核心类代码示例 13
整个程序的核心代码二 15
如何将TestRunner 中的测试信息显示在界面上 16
使用ADT 运行测试单元 17
通过AVD 运行测试单元 18
通过adb shell 命令运行测试单元 21
错误提示说明 21
Runtest介绍 23
什么是Instrumentation 27
android.app包中Instrumentation类结构,如下图所示 27
代码覆盖率测试 29
什么是 JUnit
JUnit是采用测试驱动开发的方式,也就是说在开发前先写好测试代码,主要用来说明被测试的代码会被如何使用,错误处理等;然后开始写代码,并在测试代码中逐步测试这些代码,直到最后在测试代码中完全通过。
现简要说明JUnit的4大功能
> 管理测试用例。修改了哪些代码,这些代码的修改会对哪些部分有影响,通过JUnit将这次的修改做个完整测试。这也就JUnit中所谓的TestSuite。
> 定义测试代码。这也就是JUnit中所谓的TestCase,根据
源代码的测试需要定义每个TestCase,并将TestCase添加到相应的TestSuite方便管理。
> 定义测试环境。在TestCase测试前会先调用"环境"配置,在测试中使用,当然也可以在测试用例中直接定义测试环境。
> 检测测试结果。对于每种正常、异常情况下的测试,运行结果是什么、结果是否是我们预期的等都需要有个明确的定义,JUnit在这方面提供了强大的功能。
以上部分与我们平常使用IDE调试的过程是完全一样的,只不过是增加了测试用例管理、测试结果检测等功能,提高了单元的效率,保证了单元测试的完整性,明确了单元测试的目标。
结合主要功能,举个简单的例子分析如下:
源代码:
public class SampleCalculator
{
public int add(int augend , int addend)
{return augend + addend ;}
public int subtration(int minuend , int subtrahend)
{ return minuend - subtrahend ;}
}
测试用例(TestCase):
import junit.framework.TestCase;
public class TestSample extends TestCase
{
private int a;
private int b;
private int r1,r2;
void setUp() /*开始测试当前用例-初始化测试环境*/
{
a = 50;
b = 20;
r1 = 70;
r2 = 30;
}
void tearDown()/*当期用例测试结束*/
{}
public void testAdd()/*测试SampleCalculator 类的Add函数*/
{
SampleCalculator calculator = new SampleCalculator();
int result = calculator.add(a , b);
assertEquals(r1 , result);/*检测测试结果*/
}
public void testSubtration()/*测试SampleCalculator 类的Subtration函数*/
{
SampleCalculator calculator = new SampleCalculator();
int result = calculator.subtration(a , b);
assertEquals(r2 , result);/*检测测试结果*/
}
}
以上TestSample测试用例中就对SampleCalculator进行了完整的单元测试,并对测试结果做了预期说明。
TestCase的管理
import junit.framework.Test;
import junit.framework.TestSuite;
public class TestAll
{
public static Test suite()
{
TestSuite suite = new TestSuite("TestSuite Test");
suite.addTestSuite(TestSample.class);
return suite;
}
}
以上就将TestSample增加到"TestSuite Test"中,将来在选择测试用例的过程中只要选择了TestSuite Test,TestSample就将加入当前测试中。如果将来SampleCalculator增加了其他功能,只需要在TestSample增加相应的测