junit学习(3.x)

时间:2022-11-30 11:58:32

自动化测试

测试所有测试类

 import junit.framework.TestCase;
import junit.framework.Assert; /**
*测试类必须要继承TestCase类
*在junit3.8中,测试方法需要满足以下原则:
*1、public
*2。void
*3.无方法参数
*4.方法名称必须以test开头
*执行每个测试用例前会调用setup方法,后会调用tearDown方法
*/
public class CalculatorTest extends TestCase {
private Calculator cal;
public CalculatorTest(String name){
super(name);
}
@Override
public void setUp() throws Exception {
cal=new Calculator();
}
public void testAdd(){
int result=cal.add(2, 3);
Assert.assertEquals(5, result);
}
public void testSubtract(){
int result=cal.subtract(2, 3);
Assert.assertEquals(-1, result);
}
public void testMutiply(){
int result=cal.multiply(2, 3);
Assert.assertEquals(6, result);
}
public void testDivide(){
int result=0;
try {
result = cal.divide(6, 2); } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Assert.fail();
}
Assert.assertEquals(3, result);
}
/**
* Throwable为错误和异常的父类
*/
public void testDivideByZero(){
Throwable tx=null;
try {
cal.divide(2, 0);
Assert.fail();
} catch (Exception e) {
tx=e;
e.printStackTrace();
}
Assert.assertEquals(Exception.class,tx.getClass());
Assert.assertEquals("除数不能为0", tx.getMessage());
}
}

添加进自动化测试

 import junit.extensions.RepeatedTest;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.framework.Test; /**
* 自动化测试
*
*/
public class TestAll extends TestCase {
public static Test suite(){
TestSuite suite=new TestSuite();
suite.addTestSuite(CalculatorTest.class);
suite.addTestSuite(LargestTest.class);
suite.addTestSuite(DeleteAllTest.class);
//重复执行CalculatorTest里的testAdd方法的次数
suite.addTest(new RepeatedTest(new CalculatorTest("testAdd"), 20));
return suite;
}
}