2016-02-15 105 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