Generating a processInstance Object in a Test Class: A Guide

Suppose there is a transaction named “foo”. To initiate its processing, we execute the method “ProcessInstance startProcessInstanceByKey(String processDefinitionKey)”, which returns the processInstanceId of the workflow. After this, the foo transaction is saved to the DB. To proceed with the next approval, we need to find the taskId associated with the processInstanceId. How can we obtain this taskId? The foo transaction must use the “void complete(String taskId, Map variables);” method to complete the task.

Question:

What is the procedure to generate the processInstance object in a test class?

The insertion was unsuccessful due to a missing required field, as indicated by the error message:
Required fields are missing
. The error occurred on the first row, specifically on the fields ProcessDefinitionId and CurrentNodeId, which are both required.


Solution:

Have a glance at this instance of Apex Approval Processing.

The recommended approach (according to the documentation) is to utilize the

Approval.Process

method.

public class ApprovalExample {
    void submitAndProcessApprovalRequest() {
        // Insert an account
        Account a = new Account(Name='Example');
        insert a;
        User user1 = [SELECT Id FROM User WHERE Alias='example'];
        // Create an approval request for the account
        Approval.ProcessSubmitRequest req1 = 
            new Approval.ProcessSubmitRequest();
        req1.setComments('Submitting request for approval.');
        req1.setObjectId(a.id);
        // Submit on behalf of a specific submitter
        req1.setSubmitterId(user1.Id); 
        // Submit the record to specific process and skip the criteria evaluation
        req1.setProcessDefinitionNameOrId('Example_Process');
        req1.setSkipEntryCriteria(true);
        // Submit the approval request for the account
        Approval.ProcessResult result = Approval.process(req1);
        // Now you have a ProcessInstance record
}

Frequently Asked Questions