Junit单元测试学习笔记(一)
l 使用方法
下载junit
https://github.com/junit-team/junit/wiki/Download-and-Install
使用junit jar包
l 一个简单的test
1.创建类
public class calc { /** * @param args */ public static int add(int first_num,int second_num) //add method { return first_num+second_num; } public static int minus(int first_num,int second_num) //minus method { return first_num-second_num; } public static int multiplication(int first_num,int second_num) //multiplication method { return first_num*second_num; } public static int division(int first_num,int second_num) { return first_num/second_num; // division will throw ArithmeticException when the second_num=0 } public static Boolean endless_loop() //endless loop { for(;;); //junit time out } }
2.创建test case
TestCase类给我们提供了setUp方法和tearDown方法,setUp方法的内容在测试你编写的TestCase子类的每个testXxxx方法之前都会运行,而tearDown方法的内容在每个testXxxx方法结束以后都会执行。
我们创建setUp方法:
import static org.junit.Assert.*; import org.junit.Before; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; public class calcTest { @Test public void testAdd() { assertEquals(5, calc.add(2,3)); } @Test public void testMunius() { assertEquals(5, calc.minus(2,3)); } @Ignore("testMultiplication() Not yet implemented") //ignore this case @Test public void testMultiplication() { assertEquals(6, calc.multiplication(2,3)); } @Test(expected=ArithmeticException.class) // catch ArithmeticException exception public void testDivision () throws Exception { assertEquals(-1, calc.division(2,0)); } @Test(timeout = 10000) //defined time out =10 seconds public void testEndless_loop() { assertTrue("true",calc.endless_loop()); // can’t return within 10 seconds } }
3.结果
If add “@Ignore("testMultiplication() Not yet implemented") “
Then the test case will be ignored.
转载请注明出处:http://www.cnblogs.com/tobecrazy/