Sub topic 14
Testing Validation Rules with Apex
This chapter assumes you can read basic Apex, know how to create an Opportunity record, and have already written a validation rule such as "Amount is required in Negotiation/Review". It also assumes you know that a bypass custom permission can skip a rule.
Why test rules in Apex
A validation rule can be clicked through by hand, but that does not repeat. Someone may later edit the formula and break it without noticing. An Apex test runs on every deployment and tells you when a rule stops doing its job. Tests also need to cover the paths a user might not try, such as a bypass or a bulk load.
A good rule test checks two things: bad data is rejected, and good data is accepted.
Capture the failure with Database.insert
A plain insert statement throws a DmlException when a rule fails. You can catch it, but Database.insert with allOrNone set to false is simpler. It returns a Database.SaveResult and does not throw, so you can inspect the outcome.
@IsTest
private class OpportunityValidationTest {
@IsTest
static void rejectsMissingAmountInNegotiation() {
Opportunity opp = new Opportunity(
Name = 'Test Opp',
StageName = 'Negotiation/Review',
CloseDate = Date.today().addDays(30)
);
Test.startTest();
Database.SaveResult result = Database.insert(opp, false);
Test.stopTest();
System.assert(!result.isSuccess(), 'Insert should fail validation');
System.assertEquals(
StatusCode.FIELD_CUSTOM_VALIDATION_EXCEPTION,
result.getErrors()[0].getStatusCode()
);
}
}The status code FIELD_CUSTOM_VALIDATION_EXCEPTION is what Salesforce reports when a validation rule blocks a save. Checking it confirms the failure came from a rule and not from some other problem, such as a missing required field.
Test the passing case too
A test that only checks failure would still pass if the rule blocked every save. Add a second method with valid data and assert success.
@IsTest
static void acceptsPositiveAmountInNegotiation() {
Opportunity opp = new Opportunity(
Name = 'Test Opp',
StageName = 'Negotiation/Review',
CloseDate = Date.today().addDays(30),
Amount = 5000
);
Database.SaveResult result = Database.insert(opp, false);
System.assert(result.isSuccess(), 'Valid record should save');
}Put this method inside the same test class.
Check the message
You can also assert on the error text, which protects the message users see.
String message = result.getErrors()[0].getMessage();
System.assert(message.contains('Amount'), 'Message should mention Amount');Keep such checks loose. An exact match breaks whenever someone improves the wording.
Test the bypass
If a rule honors a custom permission, test that path. Create a permission set that grants the permission and assign it to the running user, then run the insert inside System.runAs.
flowchart TDThe diagram block above is not used. Follow these steps instead:
- Create a
PermissionSetand aSetupEntityAccessrecord that points to theCustomPermission. - Create a
PermissionSetAssignmentfor the test user. - Call
System.runAs(user)and insert the invalid record. - Assert that the save now succeeds.
Insert the permission set records before System.runAs. Setup objects and regular records in the same transaction can trigger a mixed DML error, which is why the user-related inserts are kept apart from the data under test.
Common errors
| Symptom | Likely cause |
|---|---|
| Test fails with an unrelated required-field error | The test record is missing a field the org requires, so the failure is not from your rule |
| Passing test fails unexpectedly | Another rule, flow, or trigger in the org rejects your test data |
| Bypass test still fails | The permission set was not assigned, or the assignment ran in the same context as the DML |
| Test passes but the rule is wrong | Only the failing case was tested |
Keep tests independent
Create the records inside the test. Tests do not see org data by default, and relying on it makes them fragile. Use a small factory method if many tests need the same valid record.
Exercise
Why should a validation rule test use Database.insert(record, false) and check the status code instead of only checking that the insert failed?
Show answer
Database.insert with allOrNone set to false returns a SaveResult instead of throwing, so the test can inspect the errors. Checking for FIELDCUSTOMVALIDATION_EXCEPTION shows the failure came from a validation rule and not from another cause, such as a missing required field.