JUnit三分钟教程 ---- 快速起步
JUnit是个好东西,做大点的项目离不开这东西,实际中用的时候也因为时间和人力的关系,仅仅写个TestCase(测试单元),运行一下看看就扔过去了,过后也不维护测试代码。
所用的JUnit包为3.8.2。
JUnit这东西,说复杂也复杂,说简单也简单,关于JUnit的叙述解说网上一堆一堆,可是就找不到个简单点又能说明问题的附带有完整代码可运行的例子。下面给出一个三分钟的入门的例子大家看看。
一、写测试目标(业务相关的类)
/**
*
* 测试对象
* User: leizhimin
* Date: 2008-3-13 14:58:58
*/
public class Calcuator {
public double add(double n1, double n2) {
return n1 + n1;
}
}
*
* 测试对象
* User: leizhimin
* Date: 2008-3-13 14:58:58
*/
public class Calcuator {
public double add(double n1, double n2) {
return n1 + n1;
}
}
二、写测试用例
import junit.framework.TestCase;
/**
* 测试用例
* File: TestCalcuator.java
* User: leizhimin
* Date: 2008-3-13 15:00:17
*/
public class TestCalcuator extends TestCase {
public void testAdd(){
Calcuator calcuator=new Calcuator();
double result=calcuator.add(1,2);
assertEquals(3,result,0);
}
}
/**
* 测试用例
* File: TestCalcuator.java
* User: leizhimin
* Date: 2008-3-13 15:00:17
*/
public class TestCalcuator extends TestCase {
public void testAdd(){
Calcuator calcuator=new Calcuator();
double result=calcuator.add(1,2);
assertEquals(3,result,0);
}
}
import junit.framework.TestCase;
/**
* 测试用例
* File: TestCalcuator2.java
* User: leizhimin
* Date: 2008-3-13 16:13:29
*/
public class TestCalcuator2 extends TestCase {
public void testAdd(){
Calcuator calcuator=new Calcuator();
double result=calcuator.add(1,2);
assertEquals(3,result,0);
}
}
/**
* 测试用例
* File: TestCalcuator2.java
* User: leizhimin
* Date: 2008-3-13 16:13:29
*/
public class TestCalcuator2 extends TestCase {
public void testAdd(){
Calcuator calcuator=new Calcuator();
double result=calcuator.add(1,2);
assertEquals(3,result,0);
}
}
三、写测试单元
import junit.framework.TestSuite;
import junit.framework.Test;
import junit.textui.TestRunner;
/**
* 测试单元
* File: TestAll.java
* User: leizhimin
* Date: 2008-3-13 16:17:10
*/
public class TestAll extends TestSuite {
public static Test suite() {
TestSuite suite = new TestSuite("TestSuite Test");
suite.addTestSuite(TestCalcuator.class);
suite.addTestSuite(TestCalcuator2.class);
return suite;
}
public static void main(String args[]){
TestRunner.run(suite());
}
}
import junit.framework.Test;
import junit.textui.TestRunner;
/**
* 测试单元
* File: TestAll.java
* User: leizhimin
* Date: 2008-3-13 16:17:10
*/
public class TestAll extends TestSuite {
public static Test suite() {
TestSuite suite = new TestSuite("TestSuite Test");
suite.addTestSuite(TestCalcuator.class);
suite.addTestSuite(TestCalcuator2.class);
return suite;
}
public static void main(String args[]){
TestRunner.run(suite());
}
}
四、运行单元测试的main()方法
控制台打印出结果如下:
..
Time: 0
OK (2 tests)
Process finished with exit code 0
Time: 0
OK (2 tests)
Process finished with exit code 0
运行图形界面显示结果:
文件转载出处:http://lavasoft.blog.51cto.com/62575/65625