+ Start a Discussion
rajubalajirajubalaji 

how to write a test class for apex class and catch(exception)

Hi Everyone,

I am new to write a apex in test classes.if anyone please help me how to write a test class for below code and if possible please explain me line by line it will really helpful for me.

Apex Class:
if (Request.Parent != null) {
                    if (Request.Parent.StarID != null && Request.Parent .StarID != '') {
                        String Parent StarID = Request.Parent .StarID + '__' + environmentCode;
                        List<Hub_Parent __c> ptList = [select Id from Hub_Parent __c where StarID__c = :ParentStarID Limit 1];
                        
                        if (ptList.size() > 0) {
                            Hub_Parent __c objParent = ptList[0];
                            ParentId = objParent.Id;
                            
                            Parent DataDelete.DataDelete(objParent .Id);

catch (Exception ex) {
                System.debug('Delete Exception: ' + ex.getMessage());
                String fileId;
                if (Request.Header != null && Request.Header.FileID != null) {
                    fileId = Request.Header.FileID;
                }
                else {
                    fileId = 'Unknown';
                }
                StarTransactionDetails.CreateInboundTransactionRequest(Request.Header.TransactionType, fileId, 'Exception', reqBody, ex.getMessage(), null, null, null, environmentCode);
                if(Request != null && Request.Header != null){
                    responseJSON = InboundTransactionResponse.GetErrorResponse(Request.Header.TransactionType, Request.Header.TimeStamp, Request.Header.FileID, null, 'Error', '0056', ex.getMessage());
                }else{
                    responseJSON = ex.getMessage();
                }
            }


Thanks Inadvance,
RajuBalaji
AnudeepAnudeep (Salesforce Developers) 
Hi RajuBalaji, 

You should introduce an exception while deleting your record to cover the catch block maybe by trying to delete the record twice. Look at the following examples

https://salesforce.stackexchange.com/questions/101111/how-to-cause-dmlexception-delete

https://anilsfgeek.blogspot.com/2015/11/test-coverage-for-try-catch-blocks-in.html

Anudeep