我有一个Spring Boot应用程序,其中在Service层中有一些方法,例如:

    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);
}


但是,这并不能测试是否实际引发了异常。

最佳答案

我认为您必须存根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);
}


这样,当您调用Service方法placementService.getPlacementById(15);时,您知道MctException将封装SQLException,因此您的测试可能会引发MctException异常。

09-15 21:36