我正在尝试使用 JUnits 覆盖我的实用程序类,但自 1 天以来我无法覆盖 catch block ,而且我不明白不覆盖此 catch block 会出现什么问题有人可以帮忙吗我..
类
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);
关于java - 无法使用 Junits 覆盖 Catch block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61712743/