Sub topic 14
Testing and troubleshooting approval processes
This chapter assumes you can build an approval process in Setup and read basic Apex and SOQL. It also assumes you know the submit, approve, reject and recall flow from earlier chapters. You will learn how to test a process by hand, how to write Apex tests for it, and how to diagnose the errors people hit most often.
What you are testing
An approval process is metadata, not code. Apex tests cannot create or edit one. They can only submit records to a process that already exists in the org. That has two consequences:
- A test class depends on the configuration of the process it calls. If an admin changes the entry criteria or the approvers, the test can fail without any code change.
- Code coverage does not measure an approval process. You assert behavior instead: status, locking, field updates, and history.
| Area | What to verify |
|---|---|
| Entry criteria | A matching record enters the process. A non-matching record does not. |
| Initial submitters | Allowed users can submit. Others get an error. |
| Step routing | Each step picks the right approver for the record's data. |
| Actions | Field updates, email alerts and tasks fire on submit, approve, reject and recall. |
| Locking | The record is locked while pending and has the expected lock state afterward. |
| History | `ProcessInstance` and `ProcessInstanceStep` rows show the expected actors and statuses. |
Manual testing first
Test in a sandbox with real user records, not only your own admin user. An admin can often see or do things the real submitter cannot, which hides permission problems.
- Create test users for the submitter, each approver, and a user with neither role.
- Create records that sit just inside and just outside each entry criterion and step criterion.
- Submit as the submitter. Confirm the Approval History related list shows the expected pending step.
- Log in as the approver, or use Login As if your org allows it. Approve and reject on separate records, and confirm the actions run.
- Recall a pending request as the submitter and confirm the record unlocks and the recall actions run.
- Try to edit the record while it is pending, as a regular user and as an administrator.
If emails are part of the process, set Deliverability under Setup > Email > Deliverability to All email in the sandbox. Sandboxes default to system email only, so email alerts will not arrive otherwise.
Writing an Apex test
The test below submits an Opportunity, checks the status and lock, then approves it. It assumes a process named Discount_Approval that applies to Opportunities with an Amount of 10,000 or more. It also assumes the running user is both an allowed submitter and an approver for the first step. Adjust the names and values to your own process.
@IsTest
private class DiscountApprovalTest {
private static Opportunity makeOpp(Decimal amount) {
Opportunity opp = new Opportunity(
Name = 'Approval Test',
StageName = 'Prospecting',
CloseDate = Date.today().addDays(30),
Amount = amount
);
insert opp;
return opp;
}
@IsTest
static void submitLocksAndApproveCompletes() {
Opportunity opp = makeOpp(50000);
Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
req.setObjectId(opp.Id);
req.setSubmitterId(UserInfo.getUserId());
req.setComments('Test submission');
req.setProcessDefinitionNameOrId('Discount_Approval');
req.setSkipEntryCriteria(false);
Test.startTest();
Approval.ProcessResult submitted = Approval.process(req);
Test.stopTest();
System.assert(submitted.isSuccess(), 'Submission should succeed');
System.assertEquals('Pending', submitted.getInstanceStatus());
System.assert(Approval.isLocked(opp.Id), 'Record should be locked while pending');
System.assertEquals(1, submitted.getNewWorkitemIds().size());
Approval.ProcessWorkitemRequest wi = new Approval.ProcessWorkitemRequest();
wi.setWorkitemId(submitted.getNewWorkitemIds()[0]);
wi.setAction('Approve');
wi.setComments('Test approval');
Approval.ProcessResult approved = Approval.process(wi);
System.assertEquals('Approved', approved.getInstanceStatus());
List<ProcessInstanceStep> steps = [
SELECT StepStatus
FROM ProcessInstanceStep
WHERE ProcessInstance.TargetObjectId = :opp.Id
ORDER BY CreatedDate
];
System.assert(!steps.isEmpty(), 'History should contain at least one step');
}
@IsTest
static void recordOutsideEntryCriteriaIsRejectedBySubmit() {
Opportunity opp = makeOpp(100);
Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
req.setObjectId(opp.Id);
req.setProcessDefinitionNameOrId('Discount_Approval');
req.setSkipEntryCriteria(false);
try {
Approval.process(req);
System.assert(false, 'Expected a DmlException');
} catch (DmlException e) {
System.assertEquals(StatusCode.NO_APPLICABLE_PROCESS, e.getDmlType(0));
}
}
}Points about this test:
Approval.processthrows aDmlExceptionon failure when you pass a single request. Assert one.getDmlType(0)rather than the message text, because messages can change.getNewWorkitemIds()is more reliable than queryingProcessInstanceWorkitemright after submission, and it works with multi-step processes.- If the process has more than one step, the first approval returns
Pendingagain. Loop over the new work item IDs until the status becomesApproved. - Do not hard-code what happens to the lock after final approval. It depends on the final approval actions you configured, so assert whatever your process specifies.
Testing as a specific user
To test permission-sensitive behavior, create a user and wrap the call in System.runAs. Remember that approvers and submitters are checked against the running user. A user who is not an assigned approver cannot respond to the work item, so a test that approves as the wrong user will fail even though the code is correct.
A troubleshooting workflow
Work from the outside in. Most failures come from the entry or the approver, not from the actions.
Common problems
| Symptom | Likely cause | What to check |
|---|---|---|
| `NO_APPLICABLE_PROCESS` or "No applicable approval process was found" | Entry criteria not met, process inactive, or submitter not allowed | Evaluate the criteria against the record's saved values. Confirm the process is active. Review **Allowed Submitters**. |
| `ALREADY_IN_PROCESS` | The record has a pending request | Query `ProcessInstance` for `Status = 'Pending'`. Recall or finish the request first. |
| `MANAGER_NOT_DEFINED` | The step uses the submitter's manager, but the field is empty | Fill in the Manager field on the user, or choose another approver rule. |
| `ENTITY_IS_LOCKED` when saving a record | The record is locked by a pending approval | Check `Approval.isLocked`. Recall the request, or have an administrator unlock it. |
| Record goes to the wrong approver | Step criteria are evaluated in order, and an earlier step matched | Reorder steps. Review what happens when a step's criteria do not match. |
| Email alert never arrives | Sandbox email deliverability, a wrong template, or a wrong recipient | Check **Deliverability**. Review the template and recipient list. |
| Approver cannot see the request | No access to the object, or the request went to a queue | Check the user's object permissions and the **Items to Approve** list. |
| Field update did not change the value | A validation rule or later automation blocked or overwrote it | Read the debug log for validation failures and other flows that touch the field. |
Use the debug log
Open Setup > Debug Logs, add a trace flag for the submitter and for the approver, and reproduce the problem. Look for these markers:
WF_APPROVAL_SUBMITand similarWF_APPROVAL_*lines show submission and step progress.WF_CRITERIA_BEGINandWF_CRITERIA_ENDshow whether criteria evaluated true or false.WF_FIELD_UPDATEandWF_EMAIL_ALERTshow actions that ran.VALIDATION_FAILshows a validation rule that stopped a field update.
Set the Workflow category to Finer or higher so the criteria lines appear.
Check the history with SOQL
When a user reports that "nothing happened", read the approval data directly instead of relying on the page layout:
List<ProcessInstance> instances = [
SELECT Id, Status, CompletedDate,
(SELECT StepStatus, Actor.Name, OriginalActor.Name, Comments, CreatedDate
FROM Steps
ORDER BY CreatedDate)
FROM ProcessInstance
WHERE TargetObjectId = :recordId
ORDER BY CreatedDate DESC
];
for (ProcessInstance pi : instances) {
System.debug(pi.Id + ' ' + pi.Status);
for (ProcessInstanceStep s : pi.Steps) {
System.debug(s.StepStatus + ' by ' + s.Actor.Name
+ ' (assigned to ' + s.OriginalActor.Name + ')');
}
}A difference between Actor and OriginalActor shows that someone other than the assigned approver acted, for example a delegated approver or an administrator.
Habits that prevent problems
- Test every branch: each step's criteria, approve, reject, and recall. Do not test only the happy path.
- Use records at the boundary of each criterion, such as an Amount exactly at the threshold.
- Keep approvers in named queues or roles instead of individual users, so test and production behave alike.
- Record the process name and its expected steps in a comment next to the test, so the next admin knows what to update.
- After every change, activate the new version and re-run the test class. Remember that an active process cannot be edited freely, so deactivating it is sometimes needed before changes.
Exercise
A test submits an Opportunity with an Amount of 5,000 to a process whose entry criteria require Amount of at least 10,000. The test fails with a DmlException. What status code do you expect, and how would you assert that in the test?
Show answer
Expect StatusCode.NOAPPLICABLEPROCESS. Wrap Approval.process in try/catch, catch DmlException, and assert System.assertEquals(StatusCode.NOAPPLICABLEPROCESS, e.getDmlType(0)). Also add a System.assert(false) after the call so the test fails if no exception is thrown.
Exercise
After a pending approval, an integration user gets ENTITYISLOCKED when updating the record. Name two ways to resolve this, and one way to confirm the lock cause in Apex.
Show answer
Recall the pending request, or have an administrator unlock the record, or let the approval finish. Confirm the cause by calling Approval.isLocked(recordId), or by querying ProcessInstance for a Pending status where TargetObjectId matches the record.