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.
9 risposte