简体   繁体   中英

How to make a unit test for a method that is catching Exception.class?

I am unit testing a class which is as below :

class ClassUnderTest {
    public SomeOtherClass var;
    public String methodUnderTest(){
        try {
            //call to some other method that throws CustomException
            String localvariable = var.someOtherMethod() //throws CustomException
            // generic operations on localvariable which can throw Exception
        } catch (CustomException e) {
            s.o.p(e);
        } catch (Exception e) {
            s.o.p(e);
        }

    }
}

The problem arises when I have to test the methodUnderTest for catching Exception.class. I can not mock SomeOtherClass to throw Exception as Exception is a checked exception and someOtherMethod throws only CustomException. How can I make a test case for this scenario ?

You donot show the signature of someOtherMethod , but if it doesn't declare any checked exceptions then it cannot throw any checked exceptions, so why test for them.

Just throw a RuntimeException to test the 2nd catch block instead.

The other exceptions you listed in your comment:

But the methodUnderTest does some generic operations after invoking someOtherMethod. It is here that the methodUnderTest is susceptible to an Exception like NPE or IndexOOB

Both NullPointerException and IndexOutOfBounds exceptions are cases of the unchecked Exception type RuntimeException . You can throw an unchecked exception from your mock by instructing your mock to throw a new RuntimeException() (Depending on what mocking framework you're using, the usage will be different).

If you end up doing this, you should also modify your catch to catch RuntimeExceptions instead of Exceptions to be more clear about the intent of your try/catch block.

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