Tuesday 4 July 2017

What is a System.runAs() Method in Apex?

Generally, all Apex code runs in system mode, and the permissions and record sharing of the current user are not taken into account. The system method, System.runAs(), lets you write test methods that change user contexts to either an existing user or a new user. All of that user’s record sharing is then enforced. You can only use runAs in a test method. The original system context is started again after all runAs() test methods complete.

Example :

System.runAs(Annappa) {

// The following code runs as user 'Annappa'

System.debug('Current User: ' + UserInfo.getUserName());

System.debug('Current Profile: ' + UserInfo.getProfileId()); }

// Run some code that checks record sharing

}
Special Note:
                       Please check these two Links:

https://salesforce.stackexchange.com/questions/88642/system-runasnew-userid-userinfo-getunserid

https://salesforce.stackexchange.com/questions/13318/error-mixed-dml-operation-on-setup-and-non-setup-objects

I hope you enjoyed the post :)