Android、JUnit深入浅出 JUnit例子分析
2010-05-26 02:25:00 来源:WEB开发网在前一篇文章JUnit初步解析中,我们简要了解了JUnit的主要功能:
管理测试用例;
定义测试代码;
定义测试环境;
检测测试结果;
结合主要功能,举个简单的例子分析如下:
源代码:
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;
更多精彩
赞助商链接