2016-10-10 77 views
0

單元測試我有一個春天啓動應用程序,我有我的服務層等的方法:對拋出的異常

public List<PlacementDTO> getPlacementById(final int id) throws MctException { 
    List<PlacementDTO> placementList; 
    try { 
     placementList = placementDao.getPlacementById(id); 
    } catch (SQLException ex) { 
     throw new MctException("Error retrieving placement data", ex); 
    } 
    return placementList; 
} 

什麼是單元測試的最好方法是MctException將被拋出?我試過了:

@Test(expected = MctException.class) 
public void testGetPlacementByIdFail() throws MctException, SQLException { 
    when(placementDao.getPlacementById(15)).thenThrow(MctException.class); 
    placementService.getPlacementById(15); 
} 

但是,這並沒有測試實際拋出異常的權利。

+1

「[...]這並沒有測試實際拋出異常的權利。」 - 你到底什麼意思?您使用正確的方法(通過'@Test(...)'註釋)來測試異常,並且此註釋確實檢查是否引發了正確的異常。 – Turing85

+2

應該是'when(placementDao.getPlacementById(15))。thenThrow(SQLException.class);'dao拋出一個SQLException,然後由MctException包裝並由該方法拋出。 – Compass

+0

謝謝指南針......這是我一直在尋找的行爲。 –

回答

1

我認爲你必須存根placementDao.getPlacementById(15)呼叫扔SQLException,而不是你MctException,像這樣:

@Test(expected = MctException.class) 
public void testGetPlacementByIdFail() throws MctException, SQLException { 
    when(placementDao.getPlacementById(15)).thenThrow(SQLException.class); 
    placementService.getPlacementById(15); 
} 

這樣,當你打電話給你的服務方法placementService.getPlacementById(15);你知道你的MctException將封裝SQLException因此您的測試可能會引發MctException異常。

+0

謝謝......這就是我一直在尋找的行爲。我以爲我曾嘗試過,但顯然不是! :-) –

1

您可能想要試用Junit的ExepctionException規則功能。這樣可以在單元測試中驗證您的異常處理的粒度大於預期的異常註釋。

@Rule 
public ExpectedException thrown= ExpectedException.none(); 

@Test 
public void testGetPlacementByIdFail(){ 
    thrown.expect(MctException.class); 
    thrown.expectMessage("Error retrieving placement data"); 
    //Test code that throws the exception 
} 

正如上面的代碼片段所顯示的,您還可以測試異常的各種屬性,如其消息。