JUnit 4 in 60 Seconds(翻译)

原文:www.cavdar.net/2008/07/21/junit-4-in-60-seconds/

这个周末我研究了一下junit 4,下面是一个简短介绍:

  1. @Test
    用@Test 注解标注你的测试用例集。测试用例不再需要“test"前缀。并且,你的测试用例集类不再需要继承”TestCase"类。
    1. @Test   
    2. public void addition() {  
    3.      assertEquals(12 , simpleMath.add( 7 , 5 ));  
    4. }  
    5.   
    6. @Test   
    7. public void subtraction() {  
    8.      assertEquals(9 , simpleMath.substract( 12 , 3 ));  
    9. }  
  2. @Before and @After
    分别使用 @Before 和 @After 注解标注 “setup” 和 “tearDown” 方法。他们分别在每个测试用例执行前和结束后运行。
    1. @Before   
    2. public void runBeforeEveryTest() {  
    3.      simpleMath = new SimpleMath();  
    4. }  
    5.   
    6. @After   
    7. public void runAfterEveryTest() {  
    8.      simpleMath = null ;  
    9. }  
  3. @BeforeClass and @AfterClass
    分 别使用 @BeforeClass 和 @AfterClass 注解标注测试用例集范围的 “setup” 和 “tearDown” 方法。 把他们看做在测试用例集中只执行一次的 setup 和 tearDown 方法。他们分别在测试用例集中所有测试用例执行前和结束后执行一次。
    1. @BeforeClass   
    2. public static void runBeforeClass() {  
    3.     // run for one time before all test cases   
    4. }  
    5.   
    6. @AfterClass   
    7. public static void runAfterClass() {  
    8.     // run for one time after all test cases   
    9. }  
  4. 异常处理
    使用带 “expected” 参数的 @Test 注解标注期望抛出指定异常的测试用例。“expected” 参数值为希望测试用例抛出的异常的类名。
    1. @Test (expected = ArithmeticException. class )  
    2. public void divisionWithException() {  
    3.     // divide by zero   
    4.      simpleMath.divide(1 , 0 );  
    5. }  
  5. @Ignore
    使用 @Ignore 注解标注你希望忽略的测试用例。如果你愿意可以加一个字符串参数来解释忽略的原因。
    1. @Ignore ( "Not Ready to Run" )  
    2. @Test   
    3. public void multiplication() {  
    4.      assertEquals(15 , simpleMath.multiply( 3 , 5 ));  
    5. }  
  6. 超时
    给 “timeout” 参数设置一个以毫秒为单位的时间段。当测试执行时间超过该时间段时,测试失败。
    1. @Test (timeout = 1000 )  
    2. public void infinity() {  
    3.     while ( true )  
    4.          ;  
    5. }  
  7. 新增断言
    比较数组的新断言方法。如果两个数组长度相同,并且对应位置的元素相等,那么两个数组相等,否则不相等。

    public static void assertEquals(Object[] expected, Object[] actual);
    public static void assertEquals(String message, Object[] expected, Object[] actual);

    1. @Test   
    2. public void listEquality() {  
    3.      List<Integer> expected = new ArrayList<Integer>();  
    4.      expected.add(5 );  
    5.   
    6.      List<Integer> actual = new ArrayList<Integer>();  
    7.      actual.add(5 );  
    8.   
    9.      assertEquals(expected, actual);  
    10. }  
  8. JUnit4Adapter
    使用Junit4Adapter在 Junit 3 下运行Junit 4的测试。
    1. public static junit.framework.Test suite() {  
    2.     return new JUnit4TestAdapter(SimpleMathTest. class );  
    3. }  

快乐编程。 :D

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值