How to cover Catch statement in test class

  • I want to cover catch statement in test class i want code that will help us to cover all catch statement in test class in salesforce. Thanks in advance.

    All depends on what in in the code before the catch statement.

    you need to share your code and the test class you've developed so far. Main code, which you need to cover, is certainly going to help us help you. :)

  • I'd take @Novarg's answer and extend it somewhat:

    //some other code
    yourClass.someMethod('Hello');
    try {
        yourClass.someMethod(null);
    } catch (NullPointerException e) {
        System.debug ('all ok');
        return;
    }
    System.assert(false, 'a NullPointerException was expected but was not thrown');
    //some other code
    

    This waý your test won't fail, the NullPointerException is rather the expected outcome.

  • If you want your tests to cover some piece of code you have to make sure that the execution will run into this line. So in case you want to test try-catch block, you must make sure that try part will throw some exception. In this example:

    public void someMethod(String a) {
        try {
            if (a.size() == 5) {
                // do something
            }
        } catch (Exception e) {
            System.debug('something went wrong, exception: ' + e);
        }
    }
    

    the try part will throw an exception if a will be null, because you will be trying to dereference a null object(with other words: you will try to call size() method on a null object), so execution will jump into the catch part. To test this case you should do something like this in your test class:

    //some other code
    yourClass.someMethod('Hello');
    yourClass.someMethod(null);
    //some other code
    

    This will test both try and catch blocks. And it will even test the code inside your if-statement(because the size of 'Hello' is equal to 5)

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM

Tags used