單元測試我有一個春天啓動應用程序,我有我的服務層等的方法:對拋出的異常
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);
}
但是,這並沒有測試實際拋出異常的權利。
「[...]這並沒有測試實際拋出異常的權利。」 - 你到底什麼意思?您使用正確的方法(通過'@Test(...)'註釋)來測試異常,並且此註釋確實檢查是否引發了正確的異常。 – Turing85
應該是'when(placementDao.getPlacementById(15))。thenThrow(SQLException.class);'dao拋出一個SQLException,然後由MctException包裝並由該方法拋出。 – Compass
謝謝指南針......這是我一直在尋找的行爲。 –