function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
yarramyarram 

Urgent: How to do code coverage for try-catch blocks

Hi all,
I am not able to do the code coverage for catch block of my below code. how can i achive this. please help me on this.
public static void Task_ContactAddressUpdate(List<Task> tsk){
        Map<Id, List<Task>> whoIdsMap = new Map<Id, List<Task>>();
            try {
                for(Task t : tsk){
                    if(t.WhoId != null){
                        if(!whoIdsMap.containsKey(t.WhoId)){
                            List<Task> temp = new List<Task>();
                                temp.add(t);
                                whoIdsMap.put(t.WhoId, temp);
                        }
                        else {
                            whoIdsMap.get(t.WhoId).add(t);
                        }
                    }
                }
                for(Contact con : [Select Id, Name,MailingCity,MailingStreet,MailingState,MailingCountry,MailingPostalCode  from Contact where Id in :whoIdsMap.keySet()]){
                    for(Task t :whoIdsMap.get(con.Id)){
                        t.MailingCity__c = con.MailingCity;
                        t.MailingStreet__c = con.MailingStreet;
                        t.MailingState__c = con.MailingState;
                        t.MailingCountry__c = con.MailingCountry;
                        t.MailingPostalCode__c = con.MailingPostalCode;
                    }
                }
            }catch (exception e) {
                ApplicationDebugLog.customExceptionDetails(e);
                if (tsk.size() == 1)
                    tsk[0].adderror('Request could not be processed.Please contact System Admin');
                else
                    ApplicationDebugLog.customExceptionDetails(e);
            }
    }
Thanks,
Yarram.
AshlekhAshlekh
Hi,

You need to modify the code and include a Test.isRunningTest() method. By this you can get the your method is running the context of Test. and You can throw the excpetion.

eg : 
if (Test.isRunningTest()) { Integer x = 1/0; // This will throw the exception. }


-Thanks
Ashlekh Gera
yarramyarram
Hi Ashlekh Gera,

thanks for your quick reply, i am not aware of this so please guide me on this where do i have to modify my code and where do i have to put this 'if' statement code. please help me on this.

Thanks,
Yarram.
Prad NethasPrad Nethas
Hi AKG,

I tried the above one but it is not covering the catch block. Can you please guide me one this.
I am also facing the same issue. I tried passing wrong test records it is going to catch block but test coverage is not getting increased.


Thank you
Pradeep