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
Vishal SawVishal Saw 

public class OptyPreApprovalDeclined { public static Set<Id> EprocessIds = new Set<Id>(); public static void process(List<Opportunity>triggerNew, Map<Id,Opportunity>triggerOldMap){ Map<Id,Opportunity> OppMap = EprocessIds.is

help me to covered 100 % test coverage
SubratSubrat (Salesforce Developers) 
Hello Vishal ,

Can you share the whole class .

Thank you.
Vishal SawVishal Saw
public class OptyPreApprovalDeclined {
    
    public static Set<Id> EprocessIds = new Set<Id>();
    public static void process(List<Opportunity>triggerNew, Map<Id,Opportunity>triggerOldMap){
        
        Map<Id,Opportunity> OppMap = EprocessIds.isEmpty() ? getOppMap(triggerNew) : new Map<Id,Opportunity>();
        List<Email_Log__c> logEmail1 = new List<Email_Log__c>();
        Email sendgrid = new Email();
        List<EmailTemplate> theTemplate = EprocessIds.isEmpty() ? [SELECT Id,HtmlVAlue,Subject,DeveloperName,name FROM EmailTemplate WHERE DeveloperName='Opportunity_Pre_Approval_DECLINED'] : new  List<EmailTemplate>();
        List<Task> TaskToInsert = new List<Task>();
        
        for(Opportunity o : EprocessIds.isEmpty() ? triggerNew : new List<Opportunity>() ){
             System.debug('Pre_Approval__c :' + o.Pre_Approval__c);
            if(Trigger.isUpdate  &&  o.Pre_Approval__c != NULL && (o.Pre_Approval__c.equalsIgnoreCase('Declined')) && o.Pre_Approval__c != triggerOldMap.get(o.id).Pre_Approval__c &&  EprocessIds.isEmpty()){
                System.debug('Pre_Approval__c Internal :' + o.Pre_Approval__c);
                Task t = new Task();
                t.Subject = 'Pre-Approval Declined';
                t.Priority = 'Normal';
                t.ActivityDate = System.today();
                t.OwnerId = UserInfo.getUserId();
                t.WhatId = o.Id;
                String declineReasons = String.join(o.Pre_Approval_Decline_Reason__c.split(';'),  '\n \u2022 ');
                t.Description = 'Pre-Approval Decline Reason: \n\u2022 ' + declineReasons + '\n' +
                                'Pre-Approval Decline Reason Notes: ' + (String.isNotBlank(o.Pre_Approval_Decline_Reason_Notes__c) ? o.Pre_Approval_Decline_Reason_Notes__c : '');
                TaskToInsert.add(t);
                
                List<String> ToAddress = new List<String>();
                if(o.OwnerId != Null && String.isNotBlank(OppMap.get(o.Id).Owner.Email)){
                    //ToAddress.add(OppMap.get(o.Id).Owner.Email);
                    ToAddress.add('prasant.pandey@forceapozee.com');
                    //ToAddress.add('imran.siddiquee@forceapozee.com');
                }
                
                //String[] declineReasonsArray = String.join(o.Pre_Approval_Decline_Reason__c.split(';'),  '\n \u2022 ');
                //String bulletPoints = String.join(declineReasonsArray, '\n \u2022 ');
                String[] declineReasonsArray = o.Pre_Approval_Decline_Reason__c.split(';');
                List<String> declineReasonsList = new List<String>(declineReasonsArray);
                String bulletPoints = String.join(declineReasonsList, '\n \u2022 ');
                
                
                String str = theTemplate[0].HtmlValue;
                str = str.replace('{!Opportunity.Id}',(o.Id !=NULL ? o.Id : ''));
                str = str.replace('{!Opportunity.Name}',(o.Name !=NULL ? o.Name : ''));
                //str = str.replace('{!Opportunity.Pre_Approval_Decline_Reason__c}',(o.Pre_Approval_Decline_Reason__c !=NULL ? o.Pre_Approval_Decline_Reason__c : ''));
                str = str.replace('{!Opportunity.Pre_Approval_Decline_Reason__c}', '\n ' + declineReasons + '\n' );
                str = str.replace('{!Opportunity.Pre_Approval_Decline_Reason_Notes__c}',(o.Pre_Approval_Decline_Reason_Notes__c !=NULL ? o.Pre_Approval_Decline_Reason_Notes__c : ''));
                
                String SubStr = theTemplate[0].Subject.replace('{!Opportunity.Name}',(o.Name !=NULL ? o.Name : ''));
                
                Map<String,String> customArgs = new Map<String,String>();
                customArgs.put('Template Id', theTemplate[0].id);
                customArgs.put('Template Subject', theTemplate[0].Subject);
                customArgs.put('Template Name', theTemplate[0].name);
                sendgrid.setCustomArguments(customArgs);
                
                sendgrid.addTo(ToAddress);
                
                sendgrid.setFrom('noreply@unitedsettlement.com');
                
                Blob tempBlob1 = Blob.valueOf(SubStr);
                string paramvalue1 = EncodingUtil.base64Encode(tempBlob1);
                sendgrid.setSubject(paramvalue1);
                Blob tempBlob = Blob.valueOf(str);
                string paramvalue = EncodingUtil.base64Encode(tempBlob);
                sendgrid.setHtml(paramvalue);
                
                try{
                    email_log__c e = SendGridV3ForTriggers.send(sendgrid, o.id);
                    logEmail1.add(e);
                }catch(exception e2){
                    system.debug('error at '+e2.getLineNumber()+' -----> '+e2.getStackTraceString()+'    due to    '+e2.getMessage());
                }
            }
            EprocessIds.add(o.Id);
        }
        if(!logEmail1.isEmpty()){
            Database.insert(logEmail1,false);
        }
        if(!TaskToInsert.isEmpty()){
            Database.insert(TaskToInsert);
        }
    }
    @TestVisible
    private static Map<Id,Opportunity> getOppMap(List<Opportunity> opp){
        Map<Id,Opportunity> OppMap = new Map<Id,Opportunity>();
        for(Opportunity o : [Select Id,Name,Pre_Approval__c,Owner.Email, OwnerId,Pre_Approval_Decline_Reason__c,Pre_Approval_Decline_Reason_Notes__c from Opportunity where Id In: opp]){
            OppMap.put(o.Id,o);
        }
        return OppMap;
    }
}

this is the class
Vishal SawVishal Saw
@isTest
private class OptyPreApprovalDeclinedTest {
  @testSetup
    Static void DataTestup(){
       
        Account acc = new Account(Name = 'Test Accounts',Email__c = 'TestAccount@TestAccount.com');
        insert acc;
        
        Contact c = new Contact();
        c.AccountId = acc.Id;
        c.FirstName = 'Fname';
        c.LastName = 'Lname';
        insert c;
       
       
        User testuser = new User(ProfileId = [SELECT Id FROM Profile WHERE Name = 'System Administrator'].Id,Title = 'title',Alias = 'alias',
                                 TimeZoneSidKey = 'America/Los_Angeles',EmailEncodingKey = 'UTF-8',LanguageLocaleKey = 'en_US',LocaleSidKey = 'en_US',
                                 LastName = 'last',Email = 'max@bupa.com',Username = 'max@bupa.com',CompanyName = 'TEST');
        insert testuser ;

        Opportunity opp = new Opportunity();
        opp.AccountId = acc.id;  
        opp.Name ='test opp1';
        opp.Closedate= System.today();
        opp.Main_Contact_Name__c = c.Id;
        opp.Pre_Approval__c ='Declined';
        opp.StageName ='Pending Cancellation';
        opp.Type_of_Debt__c = 'Consumer Debt';
        opp.Pre_Approval_Decline_Reason__c = 'Excluded Debt';    
 
        insert opp;
        
        opp.Pre_Approval__c ='Approved';
        
        update opp;
        
        Task t = new Task();
                t.Subject = 'Pre-Approval Declined';
                t.Priority = 'Normal';
                t.ActivityDate = System.today();
                t.OwnerId = UserInfo.getUserId();
                t.WhatId = opp.Id;
        insert t;
 
    }
    
    static testMethod void Process(){
       Test.startTest();
       List <Opportunity> oppList =[SELECT id,Pre_Approval__c FROM Opportunity ];
        for(Opportunity o :oppList ){
            o.Pre_Approval__c ='Declined';
            o.Pre_Approval_Decline_Reason__c = 'Unacceptable Debt';    
       }
         
         update oppList;
         Test.StopTest();
         
    }    
      
}

TestClass
SubratSubrat (Salesforce Developers) 
Hello Vishal ,

Can you try with the below test class and let me know further :
 
@isTest
public class OptyPreApprovalDeclinedTest {
    @isTest
    static void testProcess() {
        // Test data setup
        Opportunity opp = new Opportunity(
            Name = 'Test Opportunity',
            Pre_Approval__c = 'Declined',
            Pre_Approval_Decline_Reason__c = 'Reason 1; Reason 2',
            Pre_Approval_Decline_Reason_Notes__c = 'Test notes'
        );
        insert opp;
        
        // Create trigger context variables
        Map<Id, Opportunity> oldMap = new Map<Id, Opportunity>();
        oldMap.put(opp.Id, new Opportunity(Pre_Approval__c = 'Approved')); // Set the old value
        
        Test.startTest();
        OptyPreApprovalDeclined.process(new List<Opportunity>{ opp }, oldMap);
        Test.stopTest();
        
        // Verify the results
        List<Task> tasks = [SELECT Subject, Priority, ActivityDate, OwnerId, WhatId, Description FROM Task];
        System.assertEquals(1, tasks.size());
        
        List<Email_Log_c> emailLogs = [SELECT Name, Opportunity_Idc FROM Email_Log_c];
        System.assertEquals(1, emailLogs.size());
    }
    
    @isTest
    static void testProcessNoEmail() {
        // Test data setup
        Opportunity opp = new Opportunity(
            Name = 'Test Opportunity',
            Pre_Approval__c = 'Declined',
            Pre_Approval_Decline_Reason__c = 'Reason 1; Reason 2',
            Pre_Approval_Decline_Reason_Notes__c = 'Test notes'
        );
        insert opp;
        
        // Create trigger context variables
        Map<Id, Opportunity> oldMap = new Map<Id, Opportunity>();
        oldMap.put(opp.Id, new Opportunity(Pre_Approval__c = 'Approved')); // Set the old value
        
        Test.startTest();
        Test.setMock(SendGridV3ForTriggers.Mock.class, new SendGridV3ForTriggers.Mock());
        OptyPreApprovalDeclined.process(new List<Opportunity>{ opp }, oldMap);
        Test.stopTest();
        
        // Verify the results
        List<Task> tasks = [SELECT Subject, Priority, ActivityDate, OwnerId, WhatId, Description FROM Task];
        System.assertEquals(1, tasks.size());
        
        List<Email_Log_c> emailLogs = [SELECT Name, Opportunity_Idc FROM Email_Log_c];
        System.assertEquals(0, emailLogs.size()); // No emails sent
    }
}

If this helps , please mark this as Best Answer.
Thank you.