In Apex to separate code execution for test and non-test context we use the following method


Do we have any such thing for validation rules i.e the validation rule should be active only for non-test context and for test-context it should be inactive.

Any hacks/unorthodox tips would be appreciate

1 Answer 1


There are a great many ways to validate for a specific user, and I would say those are most appropriate here as well. Simply check the following in your rule:


Then, run your test as a User who has this permission assigned. You will need to add the Custom Permission to a Permission Set, then make sure this context user has it assigned.

Id permissionSetId = [
    SELECT Id FROM PermissionSet WHERE Name = 'SkipOpportunityValidations'
User contextUser = (User)SObjectFactory.create(User.sObjectType);
PermissionSetAssignment assignment = new PermissionSetAssignemnt(
    PermissionSetId=permissionSetId, AssigneeId=contextUser.Id;
    // validations will now be skipped

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .