I have created a visualforce page which has records of pending approval processes and that page has buttons which approve/ reject a request. Please guide how will I have to write test class for it and what will be the steps for it. So far I have tried creating ProcessInstance which has a required field ProcessDefinitionId and I dont know how to create a Process Definition.

Apex Class :

 public approvalProcessWidgetController() 

        listWrapper = new List<WrapperClass>();
        List<ProcessInstanceWorkitem> listpiwItem = [SELECT Id, ActorId, OriginalActorId, ProcessInstance.TargetObjectId, ProcessInstance.TargetObject.Name ,ProcessInstance.Status , ProcessInstance.CreatedDate, 
                ProcessInstance.ProcessDefinition.Name, ProcessInstance.ProcessDefinition.TableEnumOrId 
                  FROM ProcessInstanceWorkitem];
        if(listpiwItem.size() > 0) {
            for(ProcessInstanceWorkitem piwItem : listpiwItem) {
                listWrapper.add(new WrapperClass(piwItem));

Test Class :

 public static testMethod void insertOpp(){ 

        Opportunity o = new Opportunity (Name='Test', CloseDate = System.today().addDays(40), StageName = 'Closed Won');
        insert o;
        List<User> user1 = [SELECT Id FROM User Limit 1];

       if(o.StageName == 'Closed Won'){
       approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();     
       req1.setComments('Submitting record for approval.');
       req1.setNextApproverIds(new Id[] {UserInfo.getUserId()});
       approval.ProcessResult result = Approval.process(req1);

       List<Id> newWorkItemIds = result.getNewWorkitemIds();

        Approval.ProcessWorkitemRequest req2 = new Approval.ProcessWorkitemRequest();
        req2.setComments('Approving request.');
        req2.setNextApproverIds(new Id[] {UserInfo.getUserId()});

        // Use the ID from the newly created item to specify the item to be worked

        // Submit the request for approval
        Approval.ProcessResult result2 =  Approval.process(req2);

        approvalProcessWidgetController controller = new approvalProcessWidgetController();
        controller.approveIndex = 1;

        // approvalProcessWidgetController.WrapperClass objW = new approvalProcessWidgetController.WrapperClass(req2);


You cannot create a ProcessDefinition programatically, as far as I know. You would need to query for it by DeveloperName if you want to set it, but you can also not set any ProcessDefinitionId on your ProcessSubmitRequest, in which case when you submit, entry criteria for all ProcessDefinitions will be evaluated and your record will enter the first one that applies. This will throw a DmlException if none apply.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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