Apex Programming

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 :

  1.   We use System.runAs when we need to perform mixed DML operations in our test by enclosing the DML operations within the runAs block.
  2.   To bypass the mixed DML error that is otherwise returned when inserting or updating setup objects together with  other sObjects.
  3.  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

Share Post

By Jitendra

My Name is Himanshu Rana, 23 Years young, born and grow up in Ghaziabad, India. A High Spirited Salesforce Admin, Developer and a Blogger. I currently work at Wakencode Technologies,

Leave a Reply

Your email address will not be published. Required fields are marked *