function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Himanshu GhateHimanshu Ghate 

Can any one tell me the proper use of system.runas with real time example,what is system.runas ,when you should use

VinayVinay (Salesforce Developers) 
Hi Himanshu,

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 only use the System.runAs method in test methods
  • When the runAs method is complete, the original system context is started again
  • System.runAs only enforces record sharing, it does not enforce field-level permissions or user permissions
  • You can bypass mixed DML operations in your test class by having the DML operations inside the System.runAs block of code
Reference:
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_tools_runas.htm
https://himanshurana.in/system-runas/

Please mark as Best Answer if above information was helpful.

Thanks,
Arun Kumar 1141Arun Kumar 1141
Hi Himanshu,

The System.runAs method in Salesforce is used to run a block of code with a specified user's context. It allows you to temporarily switch to another user's permissions and record access level for testing or performing operations that require elevated privileges.
Here's an example to illustrate the use of System.runAs:
Let's say you have a Salesforce org with different user roles and profiles. You have implemented a complex Apex trigger that performs certain operations on an object when it is created. Now, you want to test whether the trigger logic works correctly for different user scenarios.
In this case, you can use System.runAs to simulate the behavior of different users while testing the trigger.

For ex.
@isTest
private class TriggerTestingExample {
    @isTest
    static void testTriggerLogic() {
        // Create a user with specific role and profile for testing
        Profile testProfile = [SELECT Id FROM Profile WHERE Name = 'Testing Profile' LIMIT 1];
        UserRole testRole = [SELECT Id FROM UserRole WHERE Name = 'Testing Role' LIMIT 1];
        User testUser = new User(
            Alias = 'testuser',
            Email = 'testuser@example.com',
            EmailEncodingKey = 'UTF-8',
            LastName = 'Testing',
            LanguageLocaleKey = 'en_US',
            LocaleSidKey = 'en_US',
            ProfileId = testProfile.Id,
            TimeZoneSidKey = 'America/Los_Angeles',
            UserName = 'testuser@example.com',
            UserRoleId = testRole.Id
        );
        insert testUser;

        // Create a test object
        MyCustomObject__c obj = new MyCustomObject__c(Name = 'Test Object');
        insert obj;

        // Perform the test scenario with different user context using System.runAs
        System.runAs(testUser) {
            // Perform actions that need to be executed as the test user
            // This can include creating, updating, or deleting records, etc.
            // For example, test the trigger logic on the newly created object
            // and assert the expected results
            Test.startTest();
            // Perform actions to test the trigger logic
            Test.stopTest();

            // Assert the expected results
            // For example, verify that the trigger has performed the expected operations
            System.assertEquals(...);
        }
    }
}

In this example, the System.runAs block is used to execute the code as the testUser. Any operations performed within the block, such as creating records, updating fields, or triggering the execution of a trigger, will run in the context of the testUser. This allows you to test the trigger logic and ensure it behaves correctly for different user scenarios.


If this helps please mark it as a best answer,
Thanks!