如何编写Junit for Exception

时间:2016-10-27 11:14:49

标签: java junit

My Class包含以下handleException方法,我必须用完整的代码覆盖率编写JUnit。由于我是JUnit的新手,任何人都可以提供帮助

public void handleException(Exception exception, DCMRequestDTO requestDTO, DCMResponseDTO responseDTO, String callType) {
    logger.error("Exception occured for deviceId:" + requestDTO.getDeviceID() + ",RefNum:"+
            requestDTO.getRefNum() + ",Operation:" + requestDTO.getOperation() + "::" + exception.getMessage());
    exception.printStackTrace();
    String errorMessageKey = "GENERIC_EXCEPTION";
    if (exception instanceof TooManyInflightException) {
        errorMessageKey = "THROTTLE_EXCEPTION";
    } else if (exception.getCause() instanceof SocketTimeoutException ||
            (exception.getCause() != null && exception.getCause().getCause() instanceof SocketTimeoutException)) {
        errorMessageKey = "TIMEOUT_EXCEPTION";
    } else if (exception.getCause().getCause() instanceof ConnectException || exception.getCause().getCause() instanceof ConnectTimeoutException || exception.getCause().getCause() instanceof UnknownHostException || exception.getCause().getCause() instanceof MalformedURLException || exception.getCause().getCause() instanceof SocketException || (exception.getMessage().indexOf("404 Error") != -1)) {
        errorMessageKey = "CONNECTION_EXCEPTION";
    } else if(exception.getMessage().indexOf("500")!=-1){
        errorMessageKey = "INTERNAL_ERROR";
    }
    /*
     * else if (exception instanceof DCMException) { if (exception.getCause().getCause() instanceof SocketTimeoutException) { errorMessageKey = "TIMEOUT_EXCEPTION"; } else if (exception.getCause().getCause() instanceof ConnectException || exception.getCause().getCause() instanceof IOException || exception.getCause().getCause() instanceof SocketException || (exception.getMessage().indexOf("404 Error") != -1)) { errorMessageKey = "CONNECTION_EXCEPTION"; } }
     */
    // logger.error(errorMessageKey + " occured in DCMServiceImpl :: UniqueId = " + requestDTO.getUniqueId() + ", RefNum = " + requestDTO.getRefNum() + ", Operation = " + requestDTO.getOperation() + ", callType = " + callType, exception);
    // added for reset time while exception occured
    responseDTO.setErrorCode(0);
    responseDTO.setErrorString(smartGraphUtils.getProperty(errorMessageKey));
    responseDTO.setStackTrace(exception.toString());
    responseDTO.setHasJson(false);
    requestDTO.setHidResolveGetRetrains("Undetermined");
}

2 个答案:

答案 0 :(得分:1)

根据您的源代码,您需要测试中的周围类的实例:那么您应该能够调用方法handleException。 每个测试应该只包含一个断言(在最好的情况下)。这使您可以轻松了解您当前正在检查的内容。 这是一个例子:

public final class MessageBusTest {
    @Test(expected = NullPointerException.class)
    public void registerWithNullThrowsNullPointerException() {
        MessageBus.INSTANCE.register(null);
    }
}

注释@Test帮助JUnit确定类中的哪些方法是测试。在我的示例中,我使用null调用方法并期望抛出异常,因此expected = NullPointerException.class

在您的情况下,您必须例如为测试准备适当的Exception,然后使用requestDTO检查assertEquals内容,即错误字符串。

答案 1 :(得分:0)

首先,您的方法有很多流,您需要为方法中的每个流/条件编写测试,以确保处理所有方案。

下面提供了示例代码,您可以编写完整的逻辑:

import org.junit.Test;

    public class HandleExceptionText {

        @Test
        public void testHandleExceptionForTooManyInflightException()  {
            //throw TooManyInflightException exception and then call handleException()
            //Example using Mockito: when(obj.method(parms)).thenThrow(new TooManyInflightException());
            //Assert to check responseDTO values have been set
        }

        @Test
        public void testHandleExceptionForSocketTimeoutException()   {
            //throw SocketTimeoutException exception and then call handleException()
            //Example using Mockito: when(obj.method(parms)).thenThrow(new SocketTimeoutException());
            //Assert to check responseDTO values have been set
        }

        @Test
        public void testHandleExceptionForConnectTimeoutException()   {
            //throw ConnectTimeoutException exception and then call handleException()
            //Example using Mockito: when(obj.method(parms)).thenThrow(new ConnectTimeoutException());
            //Assert to check responseDTO values have been set
        }

        @Test
        public void testHandleExceptionForConnectException()   {
            //throw ConnectException exception and then call handleException()
            //Example using Mockito: when(obj.method(parms)).thenThrow(new ConnectException());
            //Assert to check responseDTO values have been set
        }

        @Test
        public void testHandleExceptionForUnknownHostException()   {
            //throw UnknownHostException exception and then call handleException()
            //Example using Mockito: when(obj.method(parms)).thenThrow(new UnknownHostException());
            //Assert to check responseDTO values have been set
        }

        @Test
        public void testHandleExceptionForMalformedURLException()   {
            //throw MalformedURLException exception and then call handleException()
            //Example using Mockito: when(obj.method(parms)).thenThrow(new MalformedURLException());
            //Assert to check responseDTO values have been set
        }

        @Test
        public void testHandleExceptionForConnectException()  {
            //throw SocketException exception and then call handleException()
            //Example using Mockito: when(obj.method(parms)).thenThrow(new SocketException());
            //Assert to check responseDTO values have been set
        }

    }

另外,我建议通过以下JUnit& Mockito教程链接: https://dzone.com/articles/junit-tutorial-beginners https://www.tutorialspoint.com/mockito/mockito_exception_handling.htm