我有这段代码,我在其中捕获了一些异常并抛出了一个自定义异常。
@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.) 删除行 Mockito.doThrow(new NumberFormatException()).when(objectMock).config();
2.) 将 JSON 文件中的客户端 ID 更改为无法转换为整数的内容。
this.instanceId = Integer.parseInt(config.getConfig().getClientId());
将因此失败并抛出异常。
关于名称的一个建议:测试方法的名称应该是 Java-Doc 中所写的名称。只需将其命名为“testCustomException”并在 Java 文档中解释方法功能。 Java 中有 Naming-Conventions(点击 here),它们基本上是通用指南。
练习这些非常有帮助,因为它可以让您在一个月左右没有编写代码后快速再次进入代码,因为它提高了可读性。
关于java - 使用 mockito 抛出运行时异常时测试是否抛出自定义异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35408376/