我有這段代碼,我捕獲了一些異常,而是拋出了一個自定義異常。當使用mockito拋出運行時異常時,測試自定義異常是否被拋出
@Override
public void config() throws CustomException{
File jsonFile = new File("config.json");
try {
ConfigMapper config = mapper.readValue(jsonFile, ConfigMapper.class);
try {
this.instanceId = Integer.parseInt(config.getConfig().getClientId());
this.configParams = config.getConfig().getConfigParams();
} catch (NumberFormatException ex) {
throw new CustomException("Please provide a valid integer for instance ID", ex);
//LOGGER.log(Level.SEVERE, "error initializing instanceId. Should be an integer " + e);
}
} catch (IOException ex) {
throw new CustomException("Error trying to read/write", ex);
// LOGGER.log(Level.SEVERE, "IOException while processing the received init config params", e);
}
}
我需要爲此編寫一個單元測試,下面是我如何編寫它。
@Test
public void should_throw_exception_when_invalid_integer_is_given_for_instanceID(){
boolean isExceptionThrown = false;
try{
Mockito.doThrow(new NumberFormatException()).when(objectMock).config();
barcodeScannerServiceMock.config();
} catch (CustomException ex) {
isExceptionThrown = true;
}
assertTrue(isExceptionThrown);
}
但它拋出一個數字格式異常,而不是我想要它的CustomException。但是,這是有道理的,因爲我使用模擬對象來拋出異常,因爲我的代碼邏輯沒有執行。但是,如果是這樣的話,我該如何測試這種情況?請指教。
我不能不同意你的命名建議 - 'testCustomException'告訴你什麼都沒有。 OP目前擁有的名稱幾乎是 – tddmonkey
@MrWiggles你知道Java有命名約定,對吧?不僅強烈建議使用**簡短明確的名稱**來表示該方法的用途,而且還要使用大寫字母代替新的單詞而不是下劃線。 – Seth
你知道我寫過一本關於良好單元測試實踐的書,對吧? – tddmonkey