Activity Forums Salesforce® Discussions What is System.RunAs () is the test class?

  • Aastha

    Member
    June 11, 2020 at 3:41 pm

    Hello Shweta,
    System.runAs() : It enable us to Changes the current user to the specified user.
    we use This Method when we need to execute the test as a context of a current user .
    When to use :
    We use System.runAs() when we need to perform mixed DML operations in our test by enclosing the DML operations within the runAs block.
    To bypass the mixed DML error that is otherwise returned when inserting or updating setup objects together with other sObjects.
    System.runas() enables you to write test methods that change the user context to an existing user .
    How To use :
    Now we will learn how we can use System.runAs() in our test class.
    Here is our test class code :
    --------------------------------------------------------------------------------------------
    @isTest
    public class YourTestClassName {
    public static testMethod void TestMethod(){
    test.startTest();
    // Fetching profile
    Id AdminProfileID = [Select Id From profile Where Name = ‘System Administrator’ Limit 1].Id;
    Id RoleID = [Select Id From UserRole Where PortalType = ‘None’ Limit 1].Id;
    //Now we are creating a user
    User l = new User(
    email=’[email protected]’,
    profileid = AdminProfileID ,
    userroleid = RoleID,
    UserName=’[email protected]’,
    alias=’Admin’,
    TimeZoneSidKey=’America/New_York’,
    LocaleSidKey=’en_US’,
    EmailEncodingKey=’ISO-8859-1′,
    LanguageLocaleKey=’en_US’,
    FirstName = ‘testAdminFirstName’,
    LastName = ‘testAdminLastName’,
    IsActive = true
    );
    insert thisUser;
    //After inserting user we insert account and perform required operation in System.runAs() method.
    System.runAs(thisUser){
    Account acc = new Account(
    Name = ‘testAcc’,
    Industry = ‘test’,
    Description = ‘test’,
    BillingStreet = ‘test’,
    BillingCity = ‘test’,
    BillingPostalCode = ‘test’,
    Website = ‘www.test.com’,
    Phone = ‘221714’,
    NumberOfEmployees = 10
    );
    insert acc;
    }
    test.stopTest();
    }
    }
    Thanks and Regards

  • Pooja

    Member
    June 11, 2020 at 4:29 pm

    This Method can be used when we need to execute the test as a context of a current user .

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos