In This post we learn about System.runAs method. when and how to use System.runAs in our Apex Test Class.
So before dive to the code. here is the short description of The method.
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.
lets illustrate with the help of an example.
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=’test@gmail.com’,
profileid = AdminProfileID ,
userroleid = RoleID,
UserName=’admin@gmail.com’,
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;
}
Contact con = new Contact(
LastName = ‘testLastName’,
FirstName = ‘testFirstName’,
AccountId = acc.Id,
Title = ‘testTitle’,
Email = ‘test@test.com’,
Phone = ‘221714’
);
System.runAs(thisUser){
insert con;
}
test.stopTest();
}
}
NOTE: You can use System.runAs Method only in test class methods.
Hits: 3746