Is it possible to use
system.runAs() methods in a trigger? If it possible please provide sample code.
- Anybody can ask a question
- Anybody can answer
- The best answers are voted up and rise to the top
This method can only be used in tests. You can find the documentation for
Short answer: no.
Longer answer: The System.runAs block was designed to support unit testing, and as such, is only allowed in a unit test context. If you're trying to impersonate another user, you would have to somehow "log in" as them and perform whatever you're doing by way of an API call. This, in turn, suggests you'd need to, at minimum, use a @future, Queueable, Schedulable, or Batchable method/class, call the API to log in as that user (I'd suggest REST here, but any of the APIs that provide a login method would be suitable), then perform whatever it is you're trying to do using that newly created session ID. This entire process is fairly trivial, but completely not obvious, and would take some initial investment in research to get it right.