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
Michael DsozaMichael Dsoza 

Test class for ProcessInstanceWorkItem

Hi,

How to write Test class for ProcessInstanceWorkItem ?
Currently we are firing query to ProcessInstanceWorkItem table to get the workitem Id and updating those records to Approve or Reject as per requirements.
Since we are not able to insert ProcessInstanceWorkItem records Also, In test class, I submiited record for an approval but in next line when I query to ProcessInstanceWorkItem for the same targetObjectId then also I am receiving 0 records.

Please help me in this to resolve this asap.

Thanks
JeffreyStevensJeffreyStevens
Probably need to share some code with us.
Michael DsozaMichael Dsoza
Thanks JeffreyStevens for looking into this...

Below is the code sample as,

public static List < Id > getWorkItemIds(Id targetObjectId, Id actorId) {
	List < Id > workitemIdList = new List < Id > ();
	for (ProcessInstanceWorkitem workItem: [Select Id FROM ProcessInstanceWorkitem WHERE ProcessInstance.TargetObjectId = : targetObjectId AND ActorId = : actorId]) {
		workitemIdList.add(workItem.Id);
	}
	return workitemIdList;
}

public static Approval.ProcessResult processRequest(Id workItemId) {
	Approval.ProcessResult process_result = null;
	try {
		Approval.ProcessWorkitemRequest request = new Approval.ProcessWorkitemRequest();
		request.setAction('Approve');
		request.setWorkitemId(workItemId);
		request.setComments('Approved');
		process_result = Approval.process(request); 
	} catch(Exception ex) {
		ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.ERROR, 'Error occurred while approving record');
	}
	return process_result;
}
  
public void approveRecord(targetId, actorId) {
	List<Id> workitemIds = getWorkItemIds(targetId, actorId);
	if(workitemIds != null && !workitemIds.isEmpty()) {
		for (ID wId: workItemIds) {
			Approval.ProcessResult pResult = processRequest(wId);
			if (process_result.isSuccess()) {
				// Record Updation Logic
				// Identify next level approver
				// Sending approval request to next level approver				
				// Send email notification
				// many more business logic...
			} else {
				ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.ERROR, 'Error occurred while approving record');
			}
		}
	} else {
		ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.ERROR, 'No Workitem exist for given targetId = ' + targetId);
	}
}

Need to write test class logic for approveRecord method.

Since I am not able to get WorkItem Ids as a result I am not able to test conditional block. 
Please let me know how can I perform INSERT operation on ProcessInstanceWorkitem to get data in query.
OR any other solution exist to write a better test class.

Thanks.
Eduardo Offermann PalmaEduardo Offermann Palma
Michael, Did you find a solution for this?