如果方法抛出异常junit嘲笑,则显示“未被测试覆盖”

问题描述

implementation class have two method :
test method call by test case and inside test() i call test2() which is throw exception,Now I want 
to 
cover this method by test case but in sonar it showing not covered by test,so how i can covered this 
method:

 [service implementation class][1]

public void test()throws SystemException {
    LOGGER.info("Testing exception");
    test2(); //not covered by test
    LOGGER.info("Testing exception 2");//not covered by test
    System.out.print("hi");//not covered by test
}

public void test2() throws SystemException {
    LOGGER.info("Testing exception");
    throw new SystemException();
}

测试用例:这是调用service.test1()方法的测试,但是在代码覆盖率中未显示 被测试覆盖:

@Test(expected = SystemException.class)
public void test1() throws SystemException  {
   service.test();      
}

解决方法

您不清楚您的问题到底是什么。当您提及“此方法”或“它”时,您必须清楚其含义。

关于您现有的代码,如果您想知道如何“覆盖”方法“ test”的最后两行,则无法覆盖它们。实际上,根本不可能执行这些行。如果方法“ test2”抛出该异常,它将退出方法“ test2”以及方法“ test”,而不会执行方法“ test”的其余部分。

为更清楚地了解您的要求,您可以尝试将方法名称更改为稍有不同,然后显式引用这些方法名称。