Activity › Forums › Salesforce® Discussions › Why we use “System.runAs” in test class in Salesforce?
-
Why we use “System.runAs” in test class in Salesforce?
Posted by chanchal kumar on August 7, 2018 at 2:39 PMWhy we use “System.runAs” in test class in Salesforce?
shradha jain replied 7 years, 9 months ago 2 Members · 1 Reply -
1 Reply
-
Hello Chanchal,
Generally, all Apex code runs in system mode, where the permissions and record sharing of the current user are not taken into account. The system method runAs enables you to write test methods that change the user context to an existing user or a new user so that the user’s record sharing is enforced. The runAs method doesn’t enforce user permissions or field-level permissions, only record sharing. You can create new users with runAs even if your organization has no additional user licenses.
You can refer the following example:
@isTest
private class TestRunAs {
public static testMethod void testRunAs() {
// Setup test data
// Create a unique UserName
String uniqueUserName = ‘standarduser’ + DateTime.now().getTime() + ‘@testorg.com’;
// This code runs as the system user
Profile p = [SELECT Id FROM Profile WHERE Name=’Standard User’];
User u = new User(Alias = ‘standt’, Email=’standarduser@testorg.com’,
EmailEncodingKey=’UTF-8′, LastName=’Testing’, LanguageLocaleKey=’en_US’,
LocaleSidKey=’en_US’, ProfileId = p.Id,
TimeZoneSidKey=’America/Los_Angeles’,
UserName=uniqueUserName);System.runAs(u) {
// The following code runs as user ‘u’
System.debug(‘Current User: ‘ + UserInfo.getUserName());
System.debug(‘Current Profile: ‘ + UserInfo.getProfileId());
}
}
}Thanks.
Log In to reply.