In Salesforce Apex testing, System.runAs() is a powerful method that allows developers to simulate different user contexts within test classes. This is essential for validating how your code behaves under various user permissions, roles, and profiles, ensuring that your application adheres to security and sharing rules.

What is System.runAs()?

System.runAs() is a method provided by Salesforce that enables you to execute a block of code as a specific user. This is particularly useful in test classes where you need to verify the behavior of your code from the perspective of different users with varying permissions and roles.

Why Use System.runAs()?

  • Validate Security and Sharing Rules: Ensure that your code respects user permissions and data visibility.
  • Simulate Different User Scenarios: Test how your application behaves for users with different profiles, roles, or permission sets.
  • Achieve Comprehensive Test Coverage: Cover various access levels and ensure that your application is robust against unauthorized access.

How to use system.runAs()?

Here is the example to use System.runAs() in apex test class: For example we have a class to create the campaign only if logged in user is marketing profile otherwise throwing error.

// Apex Trigger

trigger campaignBeforeInser on Account (before insert) {
for(Campaign campaign: trigger.new){
if(userInfo.getProfileId == ‘marketing profile Id’){
campaign.currency = ‘USD’;
}
else{
campaign.addError(‘you are not authorized to create campaign’);
}
}
}
  • Apex Trigger (campaignBeforeInsert): This trigger executes before inserting a Campaign record. It checks the profile ID of the logged-in user.
  • UserInfo.getProfileId() is used to determine the user’s profile.
  • If the user’s profile matches the marketing profile ('marketing profile Id'), it sets the campaign currency to USD.
  • If the user is not from the marketing profile, it adds an error (addError()), effectively blocking the user from creating the campaign.

//Here is the Test class for above trigger.

@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 = ‘test@test.com’;
user.email = ‘test@test.com’;
insert user;
system.runAs(user){
Campaign campaign = new Campaign();
campaign.name = ‘laptop’;
insert campaign();
}
}
}
  • Profile Selection: The test method begins by selecting a profile with the name containing “marketing” using SOQL (Profile prof = [SELECT Id FROM Profile WHERE Name LIKE '%marketing%'];). This ensures that the user being created will be a part of the marketing team.
  • User Creation: A user is then created with the selected marketing profile. Essential fields are filled, including:
    • FirstName, LastName, ProfileId, Username, Email, Alias, TimeZoneSidKey, LocaleSidKey, EmailEncodingKey, and LanguageLocaleKey.
    • After defining these fields, the user record is inserted into the system.
  • System.runAs(user): This is where System.runAs() is used. The System.runAs(user) method ensures that the code inside its block runs as if it were executed by the newly created user.
    • A new campaign is created and inserted as if the “marketing profile” user is doing it.
    • Since the user is part of the marketing profile, they will be authorized to create the campaign, and no error will occur.

Key Points About System.runAs():

  1. Simulate User Context: It is only used for testing purposes to simulate the behavior of different users, specifically their profiles, roles, and permissions.
  2. Governors and Limits: System.runAs() does not bypass normal governor limits. All limits still apply when executing in this simulated context.
  3. Test Data: System.runAs() helps ensure the test data adheres to the actual access permissions and capabilities users would have in a real scenario, which helps validate security and functionality.