March 18, 2020

Approval submission and recall using apex in Salesforce with test class

Sample Apex Class:

public class ApprovalProcessController {

    public static Approval.ProcessResult submitForApproval( Id recordId ) {
   
        Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();
        req1.setComments( 'Submitting request for approval' );
        req1.setObjectId( recordId );
        Approval.ProcessResult result = Approval.process( req1 );
        return result;

    }

    public static Approval.ProcessResult recallApproval( Id recordId ) {
   
        ProcessInstanceWorkitem[] workItems = [ SELECT Id
                                                FROM ProcessInstanceWorkitem
                                                WHERE ProcessInstance.TargetObjectId =: recordId
                                                AND ProcessInstance.Status = 'Pending' ];
        Approval.ProcessWorkitemRequest pwr = new Approval.ProcessWorkitemRequest(); 
        pwr.setAction( 'Removed' );
        pwr.setWorkItemId( workItems[0].id );       
        Approval.ProcessResult result = Approval.process( pwr );
        return result;
       
    }
   
}


Sample Apex Test Class:

@isTest
private class ApprovalProcessControllerTest {

    static testMethod void testApproval() {
   
        Opportunity opp = new Opportunity( Name = 'Test', CloseDate = System.Today().addDays( 3 ) );
        opp.StageName = 'Prospecting';
        opp.OwnerId = '0056g000003zzqiAAA';
        insert opp;       
        Approval.ProcessResult result = ApprovalProcessController.submitForApproval( opp.Id );
        System.assert( result.isSuccess() );       
        System.assertEquals( 'Pending', result.getInstanceStatus() );   
        result = ApprovalProcessController.recallApproval( opp.Id );
        System.assert( result.isSuccess() );       
        System.assertEquals( 'Removed', result.getInstanceStatus() );       
       
    }

}

No comments:

Post a Comment