What is System.runAs() and Why use?
Ans:- Actually, 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 :-
1
|
System.runAs(user) {
|
|
2
|
// The following code runs as user
'user'
|
3
|
System.debug('Current User: ' +
UserInfo.getUserName());
|
|
4
|
System.debug('Current Profile: ' +
UserInfo.getProfileId()); }
|
5
|
// Run some code that checks record
sharing now
|
|
6
|
}
|
No comments:
Post a Comment