无法使用Junits覆盖捕获块 [英] Not able to cover Catch block using Junits

查看:61
本文介绍了无法使用Junits覆盖捕获块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用JUnits覆盖我的Utility类,但是自1天以来我就无法覆盖捕获块,而且我不了解不覆盖该捕获块有什么问题可以帮上忙我..

I am trying to cover my Utility class using JUnits but i am not able to cover catch block since 1 day and i am not understanding what is problem for not covering this catch block can some one help me..

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

Use null instead of new Object() in above statement, you should get NullPointerException

CustomStringConverter.objectToJsonString(null);

这篇关于无法使用Junits覆盖捕获块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆