Monday, October 4, 2021

How to cover try and catch block coverage in apex test class salesforce

This post explains how to cover the apex try and catch block in salesforce.

Sometimes It becomes important to handle the catch block to complete 75 percent coverage in apex class. There are two lines of code you have to implement in apex class in order to cover both try and catch blocks.
  • First you have to create a custom exception class.
  • Use Test.isRunningTest() at the end of your try block. This statement will only run when you are running a test class.
  • In Test.isRunningTest() throw a custom exception which you have created in earlier steps.
NOTE: The code is only based on that you want to cover both try and catch blocks.

SampleClass.apx :


public class SampleClass {
    //create custom exception class
    class MyException extends Exception{}
    public static void Testing(){
        try
            {
                String s = 'In try block';
                system.debug(s);
                // When test class is running it throw an exception
                if(Test.isRunningTest())
                {
                    throw new MyException();
                }
            }
        catch(Exception e)
            {
                String s = 'In catch';
                system.debug(s);
            }
    }
}

SampleClassTest.apx :


@isTest
public class SampleClassTest {
    Public  static testmethod void testSapIntegration(){
        SampleClass.Testing();
    }
}

Output :

Cover try catch block in apex test class


Thanks, 
Lovesalesforceyes

No comments:

Post a Comment

Get selected radio button value in LWC

This post explains how to get selected radio button in LWC. Below is demo of output : To use the radio button in LWC you have to use the  li...