首页 > 解决方案 > 无法使用 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;
        }
    }

}

标签: javajunit

解决方案


CustomStringConverter.objectToJsonString(new Object());

在上面的语句中使用 null 而不是 new Object(),你应该得到 NullPointerException

CustomStringConverter.objectToJsonString(null);

推荐阅读