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


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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.