2016-02-15 106 views
2

我有這段代碼,我捕獲了一些異常,而是拋出了一個自定義異常。當使用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。但是,這是有道理的,因爲我使用模擬對象來拋出異常,因爲我的代碼邏輯沒有執行。但是,如果是這樣的話,我該如何測試這種情況?請指教。

回答

2

1)拆下線Mockito.doThrow(new NumberFormatException()).when(objectMock).config();

2)在你的JSON-文件更改客戶ID的東西,不能轉換爲整數。

this.instanceId = Integer.parseInt(config.getConfig().getClientId());將因此失敗,從而引發異常。

有關名稱的建議:您的測試方法的名稱應該是Java-Doc中的內容。只需將其命名爲「testCustomException」&即可解釋Java文檔中的方法功能。在Java中有命名約定(點擊here),這些基本上是一般的指導原則。

實踐這些非常有幫助,因爲它允許您在由於提高的可讀性而在一個月左右的時間內無法工作而再次快速進入您的代碼。

+1

我不能不同意你的命名建議 - 'testCustomException'告訴你什麼都沒有。 OP目前擁有的名稱幾乎是 – tddmonkey

+0

@MrWiggles你知道Java有命名約定,對吧?不僅強烈建議使用**簡短明確的名稱**來表示該方法的用途,而且還要使用大寫字母代替新的單詞而不是下劃線。 – Seth

+0

你知道我寫過一本關於良好單元測試實踐的書,對吧? – tddmonkey