java - 无法使用 Junits 覆盖 Catch 块
问题描述
我正在尝试使用 JUnits 覆盖我的实用程序类,但自 1 天以来我无法覆盖catch 块,我不明白不覆盖这个 catch 块有什么问题可以帮助我..
班级
public class CustomStringConverter {
private static final Logger LOGGER = LoggerFactory.getLogger(CustomStringConverter.class);
private CustomStringConverter() {}
public static String objectToJsonString(Object obj) {
try {
return new ObjectMapper().writeValueAsString(obj);
} catch (Exception e) {
LOGGER.error("CustomStringConverter.objectToString: Generic Exception", e);
}
return AccessIdConstants.EMPTY;
}
}
测试班
public class CustomStringConverterTest {
private static final String NAME = "name";
private static final String TITLE = "title";
private static final long ID = 1L;
public ErrorCollector collector = new ErrorCollector();
public ExpectedException expectedException = ExpectedException.none();
@Rule
public RuleChain ruleChain = RuleChain.outerRule(collector).around(expectedException);
@Test
public void objectToJsonStringTest() throws Exception {
TestHelper testHelper = new TestHelper();
testHelper.setId(ID);
testHelper.setName(NAME);
CustomStringConverter.objectToJsonString(testHelper);
}
@Test
public void objectToJsonStringTest_Exception() throws Exception {
// Assert
expectedException.expect(Exception.class);
ObjectMapper mapper = new ObjectMapper();
String json = "{\"name\":\"john\",\"age\":22,\"class\":\"mca\"}";
mapper.readValue(json, TestExceptionHelper.class);
CustomStringConverter.objectToJsonString(new Object());
}
class TestExceptionHelper {
String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
static class TestHelper {
String name;
long id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
}
解决方案
CustomStringConverter.objectToJsonString(new Object());
在上面的语句中使用 null 而不是 new Object(),你应该得到 NullPointerException
CustomStringConverter.objectToJsonString(null);
推荐阅读
- c - 我如何设置 Visual Studio Code 以进行简单的 C 编程?
- sql - 我怎样才能完全用 Scala (Spark) 重写这个 SQL
- android - Android:设置计时器以允许打开活动
- php - Livewire 多选表单数据
- reactjs - 我在反应中的图像不会加载到页面上。如何加载本地图像文件?
- postgresql - 重复键值违反唯一约束“x_pkey”
- uipath - 无法从网站获取 UI 元素,即注册号
- postgresql - 如何从 postgres 的两个不同列中获取百分比?
- python - 对齐结构列表以进行补丁分析
- python - Visual Studio Code - Python - Windows - Black 运行但不格式化代码