简体   繁体   中英

Catching Exception with JUnit @Test(expected=Exception.Class)

I am writing a test case using JUnit and I am trying to catch an Exception using @Test(expected=Exception.Class) . For some reason I am unable to catch the exception . If I pass null it would throw NullPointerException and the test catches it because Exception is the parent class but on my Coverage report the exception is still not covered.

Method under test:

private static final String CONTENT_LENGTH = "Content-Length";

protected long getContentLength( MultivaluedMap<String, String> headers ) {
    String length = headers.getFirst( CONTENT_LENGTH );

    if( length != null ) {
        try {
            return Long.valueOf( length );
        } catch( Exception e ) {}
    }

    return 0;
}

JUnit test case:

@Test(expected=Exception.class)
public void testGetContentLength() {
    new TestBaseMessageBodyReader().getContentLength(null);
}

Any help would be appreciated.

Thanks

Catching generic exception is bad practice and even worse to catch an exception and do nothing. in your try catch you should catch NumberFormatException which is what Long.valueOf has the potential of throwing. Even then your jUnit will not never catch the exception because you are catching the exception but not doing anything with it, the method would always return 0 as it's currently written (provided you're not passing null)

Here is some code that would catch the exception on your unit test. I'd create two unit tests, one to catch your the first exception and one to catch the second.

protected long getContentLength(MultivaluedMap<String, String> headers)
    {
        if(null == headers)
        {
            throw new SomeCustomException("some message");
        }
        Long returnValue = 0;
        String length = headers.getFirst(CONTENT_LENGTH);


            try
            {
                returnValue = Long.valueOf(length);
            }
            catch (NumberFormatException e) {
                // if you can recover handle it here 
                // if you can't recover then break the app
                throw new SomeOtherCustomException("some other message");
            }


        return returnValue;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM