Skip to main content
Conor Downey (Tier 1 CRM) 님이 #Apex에 질문했습니다
Is it possible to run Apex code under a different user than the logged in one?

So someone has logged in and they kick off some Apex code, but I need that specific method to run under an admin user? Is that possible?

Thanks.
답변 9개
  1. 2024년 10월 7일 오전 11:00

    Hi,

    In Salesforce, running Apex code under a different user context can be achieved using the System.runAs() method. 

    The System.runAs() method allows you to execute a block of code with the permissions of a specific user. 

    Suppose you have a method that needs to create a record that only an admin user should be able to create. 

    @isTest

    public class MyApexClassTest {

        @isTest

        static void testRunAsAdmin() {

            // Creating a  user with admin profile

            Profile admin = [SELECT Id FROM Profile WHERE Name = 'System Administrator' LIMIT 1];

            User adminUser = new User(

                Username = 'adminuser@example.com',

                Email = 'adminuser@example.com',

                Alias = 'adm',

                ProfileId = admin.Id,

                TimeZoneSidKey = 'America/Los_Angeles',

                LocaleSidKey = 'en_US',

                EmailEncodingKey = 'UTF-8',

                LanguageLocaleKey = 'en_US',

                FirstName = 'Admin',

                LastName = 'User',

                IsActive = true

            );

            insert adminUser;

     

            // Running the code as a newly created user

            System.runAs(adminUser) {

                MyApexClass.createRestrictedRecord(); 

            }

        }

    }

     

    Mark this helpful if it helps you.

0/9000