Last active
July 14, 2017 18:39
-
-
Save escgeek/1d698d5e01752b9081a4192d0e1065e4 to your computer and use it in GitHub Desktop.
Apex Test Classes using System.Runas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example One - Create the User and run tests under that user | |
Profile p = [select id from profile where name='System Administrator']; | |
User u = new User( | |
alias = 'abc123xyz', | |
email='unit.test@email123.com', | |
emailencodingkey='UTF-8', | |
firstname='Sam', | |
lastname='Franks', | |
languagelocalekey='en_US', | |
localesidkey='en_GB', | |
profileid = p.Id, | |
timezonesidkey='Europe/London', | |
username='unit.test@email123.com' | |
); | |
insert u; | |
System.runAs(u){ | |
Opportunity newOpp = new Opportunity( | |
Name = 'Test Opp', | |
Account = a.Id, | |
CloseDate = Date.Today() + 90, | |
Primary_Contact__c = c.Id, | |
StageName = 'Prospect', | |
Amount = 1.00, | |
Product_Family__c = 'Heavy Metal', | |
//RecordTypeId = '01244000001MMcz', <-- This is how you can statically set the record type or use a variable | |
Pricebook2 = pb | |
); | |
insert newOpp; | |
} | |
// Method to run the tests as the user executing the tests | |
User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()]; | |
System.runAs(thisUser){ | |
// Test Go Here | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment