Showing posts with label How to cover code for catch block in Apex. Show all posts
Showing posts with label How to cover code for catch block in Apex. Show all posts

Monday, March 6, 2023

How to cover code for catch block in Apex

Sometime developer needs to cover the catch part in the Apex Class.

Code Snippet:

try{
    Account acc = new Account();    
    acc.Name = 'Test';    
    Database.insert (tempList,false);
}
catch(exception e){
    LogObj obj = new LogObj();
    obj.error = e.getMessage();
    insert obj;
}

To cover the catch, we can modify the code as shown:

try{
    boolean allOrNone = false;
    Account acc = new Account();    
    acc.Name = 'Test';    
    Database.insert (tempList, allOrNone );
    if(Test.isRunningTest()){
        Database.insert (tempList, 0);
    }
}
catch(exception e){
    LogObj obj = new LogObj();
    obj.error = e.getMessage();
    insert obj;
}

In this case, code will run the Database.insert (tempList, 0); line and will eventually fail and code will go to catch block.

Please share the blog and leave a comment about your thoughts.

Click here for more blogs

Mostly Viewed