我有这段代码,我捕获了一些异常,而是抛出了一个自定义异常。当使用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