一,背景知識:
由前面的知識可以知道:
/*
* @Test:將一個普通方法修飾為一個測試方法
* @Test(exception=XXX.class)
* @Test(time=毫秒)
* @BeforeClass:它會在所有的測試方法前被執行,static修飾
* @AfterClass:它會在所有的測試方法后被執行,static修飾
* @Before:它會在每一個測試方法前被執行一次
* @After:它會在每一個測試方法后被執行一次
* @Ignore:省略
* @RunWith:修改運行器org。junit。runner。Runner
*
* */
其實@Test不僅可以修飾一個普通方法為測試方法,還可以獲取異常或者控制測試方法的執行時間
二,@Test的功能
A,獲取異常
B,控制測試代碼執行時間
A,獲取異常代碼展示
1,獲取異常,對異常的捕獲:@Test(expected=XXX.class)
1 package com.duo.util; 2 3 import static org.junit.Assert.*; 4 5 import org.junit.Test; 6 7 public class Anotation { 8 9 @Test(expected=ArithmeticException.class) 10 public void testDivide(){ 11 assertEquals(4, new Calculate().divide(12, 0)); 12 } 13 14 }
運行后結果:
2,沒有通過@Test(expected=ArithmeticException.class)注解時代碼以及結果:
1 package com.duo.util; 2 3 import static org.junit.Assert.*; 4 5 import org.junit.Test; 6 7 public class Anotation { 8 9 @Test 10 public void testDivide(){ 11 assertEquals(4, new Calculate().divide(12, 0)); 12 } 13 14 }
運行結果:
B,控制測試代碼執行時間,代碼展示
測試方法控制@Test(timeout=毫秒),主要是針對代碼中有循環代碼的測試控制或者超時運行不符合預期的判定
1,我們使用對一個死循環進行測試:
1 package com.duo.util; 2 3 import static org.junit.Assert.*; 4 5 import org.junit.Test; 6 7 public class Anotation { 8 9 @Test(timeout=2000) 10 public void testWhile(){ 11 while(true){ 12 System.out.println("run forever..."); 13 } 14 } 15 }
結果及時運行2秒后系統自動停止運行;
2,讓當前線程運行2000毫秒,測試代碼運行3000毫秒,符合預期結果
1 package com.duo.util; 2 3 import static org.junit.Assert.*; 4 5 import org.junit.Test; 6 7 public class Anotation { 8 9 @Test(timeout=3000) 10 public void testReadFile(){ 11 try { 12 Thread.sleep(2000); 13 } catch (InterruptedException e) { 14 // TODO Auto-generated catch block 15 e.printStackTrace(); 16 } 17 } 18 }
運行結果通過;
也可以通過調整測試時間比線程時間小,測試不符合預期的場景;
三,Ignore注解(該注解可以忽略當前的運行的方法,有時候改測試方法沒有實現或者以后再實現)
1 package com.duo.util; 2 3 import static org.junit.Assert.*; 4 5 import org.junit.Ignore; 6 import org.junit.Test; 7 8 public class Anotation { 9 10 @Test(expected=ArithmeticException.class) 11 public void testDivide(){ 12 assertEquals(4, new Calculate().divide(12, 0)); 13 } 14 15 @Ignore 16 @Test(timeout=2000) 17 public void testWhile(){ 18 while(true){ 19 System.out.println("run forever..."); 20 } 21 } 22 23 @Test(timeout=3000) 24 public void testReadFile(){ 25 try { 26 Thread.sleep(2000); 27 } catch (InterruptedException e) { 28 // TODO Auto-generated catch block 29 e.printStackTrace(); 30 } 31 } 32 }
運行結果:
四,RunWith,可以修改測試運行器:org.junit.runner.Runner(后面使用到再解釋)
五,斷言:assert
斷言assert的好多方法可以直接使用,主要是使用了靜態導入:import static org.junit.Assert.*;