java - 无法使用 Junits 覆盖 Catch block

标签 java junit

我正在尝试使用 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/

相关文章:

java - 在 Web 应用程序中使用 weblogic 数据源选项

java - Intellij Idea 12 IDE 谈话连接到 ejabberd

java - 存储 5 个属性的最有效方法

java - Easy mock 无法识别模拟服务

java - 使用 JUnit 时出现断言错误

java - 为采用命令行输入的 Java 独立执行 JUnit 测试用例

java - 处理 DBUnit 中的保留字符

java - AppEngine(Java)中cron作业的复杂时间表

java - 在文件读取期间强制 IOException

java - 我希望分割字符串包括 ","或 "’ "but i do not want ","or "’” 出现在我的输出中?