Not able to cover Catch block using Junits

大憨熊 提交于 2020-06-09 07:08:50

问题


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..

Class

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;
    }

}

Test class

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;
        }
    }

}

回答1:


CustomStringConverter.objectToJsonString(new Object());

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

CustomStringConverter.objectToJsonString(null);


来源:https://stackoverflow.com/questions/61707974/not-able-to-cover-catch-block-using-junits

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!