[英]Mock exception flow in jackson object mapper
这是方法
public String getProductCategoryJSON(NestedProductCategoryMap nestedProductCategoryMap) {
try {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
return objectMapper.writeValueAsString(nestedProductCategoryMap.getRoot());
} catch (Exception e) {
LOGGER.error("error-code:{} error: JSON conversion failed ", JSON_CONVERSION.getErrorCode(), e);
throw new ValidationException(ExceptionEnum.JSON_CONVERSION,e);
}
}
这是我尝试过但似乎不起作用的测试
@Test(expected = Exception.class)
public void test_getProductCategoryJSON_Should_ReturnException() throws Exception {
NestedProductCategoryMap nestedProductCategoryMap = new NestedProductCategoryMap();
nestedProductCategoryMap.makeCat(1,"(");
nestedProductCategoryMap.makeCat(2,"s2");
String json="{";
ObjectMapper objectMapperMock = Mockito.mock(ObjectMapper.class);
Mockito.when(objectMapperMock.writeValueAsString(any(NestedProductCategoryMap.class))).thenThrow(new JsonProcessingException("test"){});
Assert.assertNotEquals(json,jsonUtil.getProductCategoryJSON(nestedProductCategoryMap));
}
是否有适当的方法来执行此内部 mocking 的 jackson object 映射器
您可以重写断言异常的块:
重写这个:
ObjectMapper objectMapperMock = Mockito.mock(ObjectMapper.class);
Mockito.when(objectMapperMock.writeValueAsString(any(NestedProductCategoryMap.class))).thenThrow(new JsonProcessingException("test"){});
对此:
Exception exception = assertThrows(Exception.class, () -> {
ObjectMapper objectMapperMock = Mockito.mock(ObjectMapper.class);
Mockito.when(objectMapperMock.writeValueAsString(any(NestedProductCategoryMap.class)));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.