Run Trigger As A Specific User (or Profile)?

No, simulating another user/profile is not possible in the scenario you describe (and an undesirable platform feature for 3rd party code security reasons). You should always build backdoors into hard-fail validation rules for this reason. I prefer doing this to enforcing the logic via triggers because then the validation rules are still maintained via clicks admin, and you can do things like add error messages to specific fields.

The pattern I follow for Sys Admin manual overrides is to exclude the privileged profile(s) from the validation rule altogether (a la twamley's note). But that doesn't get you what you need, which is a code-only override.

For situations where only code is allowed to bypass a validation rule, you've mentioned the option of a hidden field but I'd suggest a significant tweak to it. I create a (18,0) numeric field called something like "Apex Updated" that is hidden from page layouts and read-only for FLS for user profiles. In any validation rule you want a code backdoor to, you just add a check for NOT(ISCHANGED(Apex_Updated__c)). Then, in your code, to bypass those validation rules you just set Apex_Updated__c to System.currentTimeMillis(). This has the advantage of not having to reset fields, or worse yet, missing the workflow to reset them and ending up with records that are permanently exempt from validation rules.

You say it's a backup plan, but it's just one custom field, one line of Apex code (to set the field when a bypass is desired), and one line of validation rule modification (to bypass the rule when the field is changed).


One option is to remove the Validation Rule entirely and enforce the same rule(s) in the trigger. This will give you more flexibility to bypass the rule as required.

If you enforce the rules in a before insert/update trigger you can use addError method to show any errors on the page or against a particular field.

You will probably want the trigger to run in what is known as the "system context". When running in this mode it won't be limited by the current users sharing rules etc...

You can alter your Apex Controllers to run in the system context by using the without sharing keywords if they are currently using with sharing.

See Using the with sharing or without sharing Keywords


UPDATE: This is only applicable to test methods

Seems like you were almost there with your "Run As" terminology.

There is a System.runAs(user) method that allows you to run tests as another user.

See Using the runAs Method.