Tuesday, August 19, 2014

How to use "System.RunAs" in test class

Ok so few times we are facing a challenge that a piece of code that we are covering in test must be run under only for some specific users. in this case we can use "System.RunAs" to over come the limitations, here is an example so we can pass it:

// This code runs as the admin user
Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator']; 
User u = new User(Alias = 'tadmins', Email='testAdmin2014@testorg.com', 
EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
LocaleSidKey='en_US', ProfileId = p.Id, 
TimeZoneSidKey='America/Los_Angeles', UserName='testAdmin2014@testorg.com');
System.runAs(u) {
// here the code for test class
}

Hope this helps you!!

No comments:

Post a Comment