测试是否在使用mockito抛出运行时异常时抛出自定义异常

时间:2016-02-15 11:37:29

标签: java unit-testing exception junit 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。但这是有道理的,因为我使用模拟对象抛出异常,因此我的代码逻辑没有被执行。但如果是这种情况,我该如何测试这种情况?请指教。

1 个答案:

答案 0 :(得分:2)

1。)删除行Mockito.doThrow(new NumberFormatException()).when(objectMock).config();

2.)将JSON-File中的Client-ID更改为无法转换为Integer的内容。

this.instanceId = Integer.parseInt(config.getConfig().getClientId());将因此而失败,从而引发异常。

关于名称的一个建议:测试方法的名称应该是Java-Doc中的名称。只需将其命名为" testCustomException" &安培;解释Java-Documentation中的方法函数。 Java中有命名约定(点击here),这些基本上是一般指导原则。

练习这些非常有用,因为它可以让你在不工作一个月左右后再次快速进入你的代码,因为可读性提高了。