-3

May I know how I can create a code coverage for if statement code? Here is my if statement code:

    @AuraEnabled
    public static void submitFinalApproval(Id recordId) {

        //1. RS
        if(String.valueOf(recordId).startsWith('a0O')){
            update new Return_Shipment__c(Id = recordId, Final_Approved__c = true); 
        }
        //2. VO__c
        if(String.valueOf(recordId).startsWith('a0G')){
            update new VO__c(Id = recordId, Final_Approved__c = true); 
        }
        //3. RPR__c
        if(String.valueOf(recordId).startsWith('a0A')){
            update new RPR__c(Id = recordId, Final_Approved__c = true); 
        }
}
1
  • 1
    Don't hardcode key prefixes. You don't even need to check them at all. Just check recordId.getSObjectType().
    – Adrian Larson
    Jun 3 at 3:24
2

You can easily make this 100% coverable by changing the code as follows:

@AuraEnabled
public static void submitFinalApproval(Id recordId) {
    sObject record = recordId.getSObjectType().newSobject(recordId);
    record.put('Final_Approved__c',true);
    update record;
}

You can read more about this in the relevant document: Dynamic DML and Dynamic Apex. Writing the unit test for this should be trivial at this point.

3
  • Thanks for your help :-)
    – Atiqah
    Jun 3 at 3:22
  • I want to ask in the sobject, I do not have any record type, do I still can use this? recordId.getSObjectType().newSobject(recordId);
    – Atiqah
    Jun 3 at 9:11
  • @Atiqah Yes, an sobjectType is not the same as a Record Type. You don't need a Record Type to use this method.
    – sfdcfox
    Jun 3 at 13:54

Not the answer you're looking for? Browse other questions tagged or ask your own question.