Activity Forums Salesforce® Discussions What is runAs() method in salesforce?

  • Shubham

    Member
    July 31, 2017 at 9:23 am

    Hi Shariq

    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 use runAs only in test methods. The original system context is started again after all runAs test methods complete.

    The runAs method ignores user license limits. You can create new users with runAs even if your organization has no additional user licenses.

    In the following example, a new test user is created, then code is run as that user, with that user's record sharing access:

    @isTest
    private class TestRunAs {
    public static testMethod void testRunAs() {
    // Setup test data
    // This code runs as the system user
    Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
    User u = new User(Alias = 'standt', Email='[email protected]',
    EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
    LocaleSidKey='en_US', ProfileId = p.Id,
    TimeZoneSidKey='America/Los_Angeles', UserName='[email protected]');

    System.runAs(u) {
    // The following code runs as user 'u'
    System.debug('Current User: ' + UserInfo.getUserName());
    System.debug('Current Profile: ' + UserInfo.getProfileId());
    }
    }

  • Himanshu Rana

    Member
    April 27, 2018 at 7:57 am

    Hey Findout below link to know about

    Apex System.Runas

  • Parul

    Member
    September 15, 2018 at 2:24 pm

    You can use runAs only in test methods. The original system context is started again after all runAs test methods complete.

    The runAs method ignores user license limits. You can create new users with runAs even if your organization has no additional user licenses.

    @isTest
    private class CampaignTriggersTest{
    private static testmethod void campaignTriggersTest(){
    Profile prof = [select id from profile where name LIKE ‘%marketing%’];
    User user = new User();
    user.firstName = ‘test1’;
    user.lastName = test2;
    user.profileId = prof.id,username = ‘[email protected]’;
    user.email = ‘[email protected]’;
    insert user;
    system.runAs(user){
    Campaign campaign = new Campaign();
    campaign.name = ‘laptop’;
    insert campaign();
    }
    }
    }

     

    Thanks

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos