Sub topic 14
Testing Validation Rules with Apex
Validation rules are logic, and logic needs tests. A rule that was correct when you built it can break when someone edits a formula, adds a record type, or changes a picklist value. An Apex test catches that before users do. It also protects deployments, because production deployments require Apex test coverage.
This chapter assumes you can read basic Apex (classes, methods, insert, List), know how to write a validation rule formula, and have access to the Developer Console or an IDE that can run tests.
What a validation test must prove
A useful test for a rule checks more than one thing:
- The rule blocks a record that breaks the business rule (the negative case).
- The rule allows a record that follows the rule (the positive case).
- The rule fails with the message or field you expect.
- Edge cases behave as designed, such as blank values, zero, and boundary values.
- Bypasses work, if the rule has one.
Testing only the negative case is a common gap. A rule that blocks everything also passes a negative-only test.
Why Database.insert with allOrNone set to false
A plain insert statement throws a DmlException when validation fails. You can catch it, but the result is verbose. Database.insert(record, false) does not throw. It returns a Database.SaveResult that you can inspect.
The false argument is the allOrNone flag. With false, the platform reports failures in the result instead of throwing an exception and rolling back the whole call.
@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()
);
}
}This test targets the rule that blocks the save when the stage is Negotiation/Review and Amount is blank or not positive. Three details matter:
- The record has no
Amount, so the rule's condition evaluates to true. result.isSuccess()isfalsewhen any error occurs.StatusCode.FIELD_CUSTOM_VALIDATION_EXCEPTIONis the status code the platform assigns to failures from validation rules. Other failures, such as a missing required field, use different codes. Checking the code confirms the failure came from a validation rule and not from something unrelated.
Test the message and the field
The status code tells you a validation rule fired. It does not tell you which one. If an object has several rules, a test can pass because a different rule rejected the record. Check the message as well:
Database.Error err = result.getErrors()[0];
System.assertEquals(
'Enter an Amount greater than zero before moving to Negotiation/Review.',
err.getMessage()
);
System.assertEquals(
new List<String>{ 'Amount' },
err.getFields()
);getFields() returns the field names for a rule whose error location is a field. For a rule shown at the top of the page, the list is empty. This lets a test lock in the error location from the rule's definition.
Asserting exact message text makes tests brittle, because a wording change breaks them. A middle path is to check err.getMessage().contains('Amount'), or to keep the message in one place that tests and rules both reference. Choose based on how often your team edits messages.
Add the positive case
Pair each negative test with one that should succeed:
@IsTest
static void allowsPositiveAmountInNegotiation() {
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: ' + result.getErrors());
}Including result.getErrors() in the assertion message makes a failure self-explaining. Without it, you see only "Valid record should save" and have to debug further.
Cover the boundaries
For the amount rule, the interesting inputs are null, 0, a negative number, and a small positive number. A loop keeps the test short:
@IsTest
static void rejectsNonPositiveAmounts() {
List<Decimal> badAmounts = new List<Decimal>{ null, 0, -1 };
for (Decimal amt : badAmounts) {
Opportunity opp = new Opportunity(
Name = 'Boundary ' + amt,
StageName = 'Negotiation/Review',
CloseDate = Date.today().addDays(30),
Amount = amt
);
Database.SaveResult result = Database.insert(opp, false);
System.assert(!result.isSuccess(), 'Amount ' + amt + ' should fail');
}
}Also test a stage other than Negotiation/Review with a blank Amount. That test proves the rule is scoped to one stage.
Testing update-only rules
Rules that use ISNEW(), ISCHANGED(), or PRIORVALUE() need a record that already exists. Insert it in a state that passes, then update it.
The rule that blocks edits to Amount unless the user holds the custom permission Can_Edit_Opportunity_Amount is a good example:
@IsTest
static void blocksAmountEditWithoutPermission() {
Opportunity opp = new Opportunity(
Name = 'Edit Test',
StageName = 'Prospecting',
CloseDate = Date.today().addDays(30),
Amount = 1000
);
insert opp;
opp.Amount = 2000;
Database.SaveResult result = Database.update(opp, false);
System.assert(!result.isSuccess(), 'Amount edit should be blocked');
}The initial insert passes because ISNEW() is true on creation, so the NOT(ISNEW()) condition is false. The update then triggers ISCHANGED(Amount). A second test should update a different field and confirm that the save succeeds.
Testing as a specific user
Tests run as the user who started them, and that user usually has broad access. To test a profile or permission-based rule, run part of the test as another user with System.runAs:
@IsTest
static void allowsAmountEditWithPermission() {
Profile p = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1];
User u = new User(
Alias = 'tstusr',
Email = '[email protected]',
EmailEncodingKey = 'UTF-8',
LastName = 'Tester',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = p.Id,
TimeZoneSidKey = 'America/Los_Angeles',
UserName = 'tstusr' + System.currentTimeMillis() + '@example.com'
);
insert u;
PermissionSet ps = new PermissionSet(
Name = 'Test_Amount_Editors',
Label = 'Test Amount Editors'
);
insert ps;
SetupEntityAccess access = new SetupEntityAccess(
ParentId = ps.Id,
SetupEntityId = [
SELECT Id FROM CustomPermission
WHERE DeveloperName = 'Can_Edit_Opportunity_Amount'
].Id
);
insert access;
insert new PermissionSetAssignment(AssigneeId = u.Id, PermissionSetId = ps.Id);
Opportunity opp = new Opportunity(
Name = 'Perm Test',
StageName = 'Prospecting',
CloseDate = Date.today().addDays(30),
Amount = 1000
);
insert opp;
System.runAs(u) {
opp.Amount = 2000;
Database.SaveResult result = Database.update(opp, false);
System.assert(result.isSuccess(), 'Permission holder should save: ' + result.getErrors());
}
}This test creates the permission set and links it to the custom permission, so it does not depend on org setup beyond the custom permission itself. The user needs access to the Opportunity object, which Standard User provides in most orgs. The same pattern tests a bypass such as Bypass_Validation_Rules: run once as a user with the permission and expect success, then as a user without it and expect failure.
The permission set inserts happen before System.runAs. Mixing setup objects such as User with other objects in one transaction can cause a mixed DML error, and System.runAs is the standard way to avoid it. If you hit that error, wrap the setup inserts in a System.runAs block for the current user.
Common test errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Negative test passes but the positive test fails | A different rule or a required field is rejecting the record | Print `result.getErrors()` and check the status code and message |
| `DmlException` thrown | Used `insert` instead of `Database.insert(..., false)` | Switch to the `Database` method or catch the exception |
| Update test never fails | The record was inserted with values that already break the rule, or no field actually changed | Insert a valid record first, then change the tested field |
| Rule never fires in test | Test user holds a bypass permission, such as an admin with a custom permission | Use `System.runAs` with a restricted user |
| Test fails only in another org | Other validation rules, required fields, or flows in that org | Set all needed fields and review the other automation |
How tests fit a deployment
Validation rules do not count toward Apex code coverage, because they are not Apex. Tests protect behavior, not coverage numbers. Still, when a deployment runs tests, a failing validation test blocks the release. This is useful: it catches a rule change that conflicts with existing code that inserts records, for example a trigger or data setup in other test classes that creates Opportunities without an Amount at that stage. A new rule can break unrelated tests for this reason. Fix them by updating the shared test data, preferably in one test data factory class.
Exercise
A rule blocks a save when ISCHANGED(Amount) is true and the user lacks a custom permission. Your test inserts an Opportunity with Amount 1000, then calls Database.update after changing only Name, and asserts that the update fails. The test fails with the assertion error. Why, and what should the test assert?
Show answer
Changing only Name does not make ISCHANGED(Amount) true, so the rule does not fire and the update succeeds. That is correct behavior. The test should assert result.isSuccess() for the Name change. A separate test should change Amount and assert failure.
Exercise
Why is Database.insert(opp, false) preferred over insert opp when testing a validation rule, and which status code confirms the failure came from a validation rule?
Show answer
With allOrNone set to false, the call returns a Database.SaveResult instead of throwing a DmlException, so the test can inspect isSuccess() and the errors. The status code StatusCode.FIELD_CUSTOM_VALIDATION_EXCEPTION identifies a validation rule failure.