2016-11-30 100 views
0

後,這是我的測試:JUnit測試代碼停止執行檢查異常

import org.junit.rules.ExpectedException; 
    @Rule 
    public final ExpectedException exception = ExpectedException.none(); 

    @Test 
    public void testSearch() { 
     List<Integer> myList = Arrays.asList(new Integer[] {1, 2, 4, 6, 3, 1, 2}); 
     exception.expect(NoSuchElementException.class); 
     SimpleSearch.search(myList, 5); 
     System.out.println("here"); 

     exception.expect(NoSuchElementException.class); 
     assertEquals(1, SimpleSearch.search(myList, 22)); 
} 

當我運行它,它說,它跑了1/1,但它不打印here,並沒有做任何斷言或者運行SimpleSearch.search(myList, 5);以下的任何行(發生異常之後)。

如何在捕獲異常後繼續執行它(我想在同一個testSearch函數中執行)?

+0

你爲什麼要繼續嗎? – developer

+0

@javaguy因爲我想測試其餘的代碼。 – user2719875

+1

將其移入單獨的方法。 – shmosel

回答

2

你的測試應該在這種情況下,更精細,並打出了2測試用例

@Test(ExpectedException=NoSuchElementException.class) 
    public void testSearch_NotFound() { 
     List<Integer> myList = Arrays.asList(new Integer[] {1, 2, 4, 6, 3, 1, 2}); 
     SimpleSearch.search(myList, 5); 
    } 

    @Test 
    public void testSearch() { 
     List<Integer> myList = Arrays.asList(new Integer[] {1, 2, 4, 6, 3, 1, 2}); 
     assertEquals(1, SimpleSearch.search(myList, 22)); 
    } 
2

該代碼按設計工作。 ExpectedException只是說:測試應該拋出這個特殊的例外,但是這樣做不是的意思是:並繼續執行。任何異常都會在此時停止執行程序。在Java中繞過這個常規方法是使用try .. catch塊。

@Test 
public void testSearch() { 

    List<Integer> myList = Arrays.asList(new Integer[] {1, 2, 4, 6, 3, 1, 2}); 
    try { 
     SimpleSearch.search(myList, 5); 
     Assert.fail("Did not find NoSuchElementException!"); 
    } 
    catch(NoSuchElementException ex) { 
     // ignored 
    } 
    System.out.println("here"); 

    // the rest of your code is nonesense 
}