Junit使用教程

       Junit目前在一些大的公司或者相對規範的軟件中使用的比較多,至關多的小公司並無把單元測試看的過重要。在大點的公司開發人員天天上班後,第一件事情就是從svn上把本身負責的代碼checkout下來,而後運行單元測試,若是單元測試經過,那麼說明本身的代碼沒有問題,而後就在代碼塊上修改與添加,完成後再用junit進行測試,測試完成後若是沒有問題,那麼就把相應的代碼塊提交給svn上。java

測試通常分爲:單元測試、集成測試(主要看一塊代碼加進去後,系統會不會有問題)、驗收測試和壓力測試。數組

 

       在之前的的項目中也用過Junit,當時的使用只是把Junit當成一個有多個main方法的一個函數。假如一個項目很是的大,測試的東西很是的多,若是不用Junit的話,那麼這個工做量是很是大的。單元測試的最基本的一個功能是能進行自動化測試。單元測試都是經過斷言的方式來肯定結果是否正確,即便用Assert。svn

 

1、創建Junit測試類函數

1. 右擊test測試包,選擇New-->Oher...oop

 

2. 在窗口中找到Junit,選擇Junit Test Case單元測試

3. 輸入名稱(Name),命名規則通常建議採用:類名+Test。Browse...選擇要測試的類,這裏是StudentService。測試

4. 勾選要測試的方法ui

5. 生成後,效果以下:this

這裏import static是引入Assert類中靜態屬性或靜態方法的寫法。原來要Assert.fail(),如今只需直接fial()便可,即省略了Assert。spa

其實不經過Junit新建嚮導來創建也能夠,隨便創建一個新類後,只需在方法上加入@Test註解便可。

 

2、核心——斷言

斷言是編寫測試用例的核心實現方式,即指望值是多少,測試的結果是多少,以此來判斷測試是否經過。

1. 斷言核心方法

assertArrayEquals(expecteds, actuals) 查看兩個數組是否相等。
assertEquals(expected, actual) 查看兩個對象是否相等。相似於字符串比較使用的equals()方法
assertNotEquals(first, second) 查看兩個對象是否不相等。
assertNull(object) 查看對象是否爲空。
assertNotNull(object) 查看對象是否不爲空。
assertSame(expected, actual) 查看兩個對象的引用是否相等。相似於使用「==」比較兩個對象
assertNotSame(unexpected, actual) 查看兩個對象的引用是否不相等。相似於使用「!=」比較兩個對象
assertTrue(condition) 查看運行結果是否爲true。
assertFalse(condition) 查看運行結果是否爲false。
assertThat(actual, matcher) 查看實際值是否知足指定的條件
fail() 讓測試失敗

2. 示例

[java]   view plain
  1. package test;  
  2.   
  3. import static org.hamcrest.CoreMatchers.*;  
  4. import static org.junit.Assert.*;  
  5.   
  6. import java.util.Arrays;  
  7.   
  8. import org.hamcrest.core.CombinableMatcher;  
  9. import org.junit.Test;  
  10.   
  11. public class AssertTests {  
  12.   
  13.       @Test   
  14.       public void testAssertArrayEquals() {  
  15.         byte[] expected = "trial".getBytes();  
  16.         byte[] actual = "trial".getBytes();  
  17.         org.junit.Assert.assertArrayEquals("failure - byte arrays not same", expected, actual);  
  18.       }  
  19.   
  20.       @Test   
  21.       public void testAssertEquals() {  
  22.         org.junit.Assert.assertEquals("failure - strings not same", 5l, 5l);  
  23.       }  
  24.   
  25.       @Test   
  26.       public void testAssertFalse() {  
  27.         org.junit.Assert.assertFalse("failure - should be false"false);  
  28.       }  
  29.   
  30.       @Test   
  31.       public void testAssertNotNull() {  
  32.         org.junit.Assert.assertNotNull("should not be null"new Object());  
  33.       }  
  34.   
  35.       @Test  
  36.       public void testAssertNotSame() {  
  37.         org.junit.Assert.assertNotSame("should not be same Object"new Object(), new Object());  
  38.       }  
  39.   
  40.       @Test  
  41.       public void testAssertNull() {  
  42.         org.junit.Assert.assertNull("should be null"null);  
  43.       }  
  44.   
  45.       @Test  
  46.       public void testAssertSame() {  
  47.         Integer aNumber = Integer.valueOf(768);  
  48.         org.junit.Assert.assertSame("should be same", aNumber, aNumber);  
  49.       }  
  50.   
  51.       // JUnit Matchers assertThat  
  52.       @Test  
  53.       public void testAssertThatBothContainsString() {  
  54.         org.junit.Assert.assertThat("albumen", both(containsString("a")).and(containsString("b")));  
  55.       }  
  56.   
  57.       @Test  
  58.       public void testAssertThathasItemsContainsString() {  
  59.         org.junit.Assert.assertThat(Arrays.asList("one""two""three"), hasItems("one""three"));  
  60.       }  
  61.   
  62.       @Test  
  63.       public void testAssertThatEveryItemContainsString() {  
  64.         org.junit.Assert.assertThat(Arrays.asList(new String[] { "fun""ban""net" }), everyItem(containsString("n")));  
  65.       }  
  66.   
  67.       // Core Hamcrest Matchers with assertThat  
  68.       @Test  
  69.       public void testAssertThatHamcrestCoreMatchers() {  
  70.         assertThat("good", allOf(equalTo("good"), startsWith("good")));  
  71.         assertThat("good", not(allOf(equalTo("bad"), equalTo("good"))));  
  72.         assertThat("good", anyOf(equalTo("bad"), equalTo("good")));  
  73.         assertThat(7, not(CombinableMatcher.<Integer> either(equalTo(3)).or(equalTo(4))));  
  74.         assertThat(new Object(), not(sameInstance(new Object())));  
  75.       }  
  76. }  

3、核心——註解

1. 說明

@Before 初始化方法
@After 釋放資源
@Test 測試方法,在這裏能夠測試指望異常和超時時間
@Ignore 忽略的測試方法
@BeforeClass 針對全部測試,只執行一次,且必須爲static void
@AfterClass 針對全部測試,只執行一次,且必須爲static void
@RunWith 指定測試類使用某個運行器
@Parameters 指定測試類的測試數據集合
@Rule 容許靈活添加或從新定義測試類中的每一個測試方法的行爲
@FixMethodOrder 指定測試方法的執行順序

2. 執行順序

一個測試類單元測試的執行順序爲:

@BeforeClass –> @Before –> @Test –> @After –> @AfterClass

每個測試方法的調用順序爲:

@Before –> @Test –> @After

3. 示例

[java]   view plain
  1. package test;  
  2.   
  3. import static org.junit.Assert.*;  
  4.   
  5. import org.junit.*;  
  6.   
  7. public class JDemoTest {  
  8.   
  9.     @BeforeClass  
  10.     public static void setUpBeforeClass() throws Exception {  
  11.         System.out.println("in BeforeClass================");  
  12.     }  
  13.   
  14.     @AfterClass  
  15.     public static void tearDownAfterClass() throws Exception {  
  16.         System.out.println("in AfterClass=================");  
  17.     }  
  18.   
  19.     @Before  
  20.     public void before() {  
  21.         System.out.println("in Before");  
  22.     }  
  23.   
  24.     @After  
  25.     public void after() {  
  26.         System.out.println("in After");  
  27.     }  
  28.   
  29.     @Test(timeout = 10000)  
  30.     public void testadd() {  
  31.         JDemo a = new JDemo();  
  32.         assertEquals(6, a.add(33));  
  33.         System.out.println("in Test ----Add");  
  34.     }  
  35.   
  36.     @Test  
  37.     public void testdivision() {  
  38.         JDemo a = new JDemo();  
  39.         assertEquals(3, a.division(62));  
  40.         System.out.println("in Test ----Division");  
  41.     }  
  42.   
  43.     @Ignore  
  44.     @Test  
  45.     public void test_ignore() {  
  46.         JDemo a = new JDemo();  
  47.         assertEquals(6, a.add(15));  
  48.         System.out.println("in test_ignore");  
  49.     }  
  50.   
  51.     @Test  
  52.     public void teest_fail() {  
  53.         fail();  
  54.     }  
  55. }  
  56.   
  57. class JDemo extends Thread {  
  58.   
  59.     int result;  
  60.   
  61.     public int add(int a, int b) {  
  62.         try {  
  63.             sleep(1000);  
  64.             result = a + b;  
  65.         } catch (InterruptedException e) {  
  66.         }  
  67.         return result;  
  68.     }  
  69.   
  70.     public int division(int a, int b) {  
  71.         return result = a / b;  
  72.     }  
  73. }  

執行結果:

[plain]   view plain
  1. in BeforeClass================  
  2. in Before  
  3. in Test ----Add  
  4. in After  
  5. in Before  
  6. in Test ----Division  
  7. in After  
  8. in AfterClass=================  

 

圖中左上紅框中部分表示Junit運行結果,5個成功(1個忽略),1個錯誤,1個失敗。(注意錯誤和失敗不是一回事,錯誤說明代碼有錯誤,而失敗表示該測試方法測試失敗)

左下紅框中則表示出了各個測試方法的運行狀態,能夠看到成功、錯誤、失敗、失敗各自的圖標是不同的,還能夠看到運行時間。

右邊部分則是異常堆棧,可查看異常信息。

 

4、實例總結

1. 參數化測試

有時一個測試方法,不一樣的參數值會產生不一樣的結果,那麼咱們爲了測試全面,會把多個參數值都寫出來並一一斷言測試,這樣有時不免費時費力,這是咱們即可以採用參數化測試來解決這個問題。參數化測試就比如把一個「輸入值,指望值」的集合傳入給測試方法,達到一次性測試的目的。

[java]   view plain
  1. package test;  
  2.   
  3. import static org.junit.Assert.*;  
  4.   
  5. import java.util.Arrays;  
  6.   
  7. import org.junit.Test;  
  8. import org.junit.runner.RunWith;  
  9. import org.junit.runners.Parameterized;  
  10. import org.junit.runners.Parameterized.Parameters;  
  11.   
  12. @RunWith(Parameterized.class)  
  13. public class FibonacciTest {  
  14.   
  15.     @Parameters(name = "{index}: fib({0})={1}")  
  16.     public static Iterable<Object[]> data() {  
  17.         return Arrays.asList(new Object[][] { { 00 }, { 11 }, { 21 },  
  18.                 { 32 }, { 43 }, { 55 }, { 68 } });  
  19.     }  
  20.   
  21.     private int input;  
  22.     private int expected;  
  23.   
  24.     public FibonacciTest(int input, int expected) {  
  25.         this.input = input;  
  26.         this.expected = expected;  
  27.     }  
  28.   
  29.     @Test  
  30.     public void test() {  
  31.         assertEquals(expected, Fibonacci.compute(input));  
  32.     }  
  33. }  
  34.   
  35. class Fibonacci {  
  36.   
  37.     public static int compute(int input) {  
  38.         int result;  
  39.         switch (input) {  
  40.         case 0:  
  41.             result = 0;  
  42.             break;  
  43.         case 1:  
  44.         case 2:  
  45.             result = 1;  
  46.             break;  
  47.         case 3:  
  48.             result = 2;  
  49.             break;  
  50.         case 4:  
  51.             result = 3;  
  52.             break;  
  53.         case 5:  
  54.             result = 5;  
  55.             break;  
  56.         case 6:  
  57.             result = 8;  
  58.             break;  
  59.         default:  
  60.             result = 0;  
  61.         }  
  62.         return result;  
  63.     }  
  64. }  

@Parameters註解參數name,實際是測試方法名稱。因爲一個test()方法就完成了全部測試,那假如某一組測試數據有問題,那在Junit的結果頁面裏該如何呈現?所以採用name實際上就是區分每一個測試數據的測試方法名。以下圖:

2. 打包測試

一樣,若是一個項目中有不少個測試用例,若是一個個測試也很麻煩,所以打包測試就是一次性測試完成包中含有的全部測試用例。

[java]   view plain
  1. package test;  
  2.   
  3. import org.junit.runner.RunWith;  
  4. import org.junit.runners.Suite;  
  5.   
  6. @RunWith(Suite.class)  
  7. @Suite.SuiteClasses({ AssertTests.class, FibonacciTest.class, JDemoTest.class })  
  8. public class AllCaseTest {  
  9.   
  10. }  

這個功能也須要使用一個特殊的Runner ,須要向@RunWith註解傳遞一個參數Suite.class 。同時,咱們還須要另一個註解@Suite.SuiteClasses,來代表這個類是一個打包測試類。並將須要打包的類做爲參數傳遞給該註解就能夠了。至於AllCaseTest隨便起一個類名,內容爲空既可。運行AllCaseTest類便可完成打包測試

3. 異常測試

異常測試與普通斷言測試不一樣,共有三種方法,其中最爲靈活的是第三種,能夠與斷言結合使用

第一種:

[java]   view plain
  1. @Test(expected= IndexOutOfBoundsException.class)   
  2. public void empty() {   
  3.      new ArrayList<Object>().get(0);   
  4. }  

第二種:

[java]   view plain
  1. @Test  
  2. public void testExceptionMessage() {  
  3.     try {  
  4.         new ArrayList<Object>().get(0);  
  5.         fail("Expected an IndexOutOfBoundsException to be thrown");  
  6.     } catch (IndexOutOfBoundsException anIndexOutOfBoundsException) {  
  7.         assertThat(anIndexOutOfBoundsException.getMessage(), is("Index: 0, Size: 0"));  
  8.     }  
  9. }  

第三種:

[java]   view plain
  1. @Rule  
  2. public ExpectedException thrown = ExpectedException.none();  
  3.   
  4. @Test  
  5. public void shouldTestExceptionMessage() throws IndexOutOfBoundsException {  
  6.     List<Object> list = new ArrayList<Object>();  
  7.   
  8.     thrown.expect(IndexOutOfBoundsException.class);  
  9.     thrown.expectMessage("Index: 0, Size: 0");  
  10.     list.get(0);  
  11.     Assert.assertEquals(1, list.get(0));  
  12. }  

在上述幾種方法中,不管是expected仍是expect都表示指望拋出的異常,假如某一方法,當參數爲某一值時會拋出異常,那麼使用第一種方法就必須爲該參數單獨寫一個測試方法來測試異常,而沒法與其餘參數值一同寫在一個測試方法裏,因此顯得累贅。第二種方法雖然解決這個問題,可是寫法不只繁瑣也不利於理解。而第三種犯法,不只能動態更改指望拋出的異常,與斷言語句結合的也很是好,所以推薦使用該方法來測試異常。

4. 限時測試

有時爲了防止出現死循環或者方法執行過長(或檢查方法效率),而須要使用到限時測試。顧名思義,就是超出設定時間即視爲測試失敗。共有兩種寫法。

第一種:

[java]   view plain
  1. @Test(timeout=1000)  
  2. public void testWithTimeout() {  
  3.   ...  
  4. }  

第二種:

[java]   view plain
  1. public class HasGlobalTimeout {  
  2.     public static String log;  
  3.   
  4.     @Rule  
  5.     public Timeout globalTimeout = new Timeout(10000); // 10 seconds max per method tested  
  6.   
  7.     @Test  
  8.     public void testInfiniteLoop1() {  
  9.         log += "ran1";  
  10.         for (;;) {  
  11.         }  
  12.     }  
  13.   
  14.     @Test  
  15.     public void testInfiniteLoop2() {  
  16.         log += "ran2";  
  17.         for (;;) {  
  18.         }  
  19.     }  
  20. }  

其中,第二種方法與異常測試的第三種方法的寫法相似。也是推薦的寫法。

 

http://huihai.iteye.com/blog/1986568

http://blog.csdn.net/wangpeng047/article/details/9627527

相關文章
相關標籤/搜索