Proposed Rule Name: ApexUnitTestClassShouldHaveRunAs
Proposed Category: [Best Practices ]
Description:
According to Salesforce best practices, when executing test method we should not rely on the user's running context.
The use of System.runAs is recommended to execute the test with a newly created user so that the test does not rely on environment data and user's configuration
Code Sample: This should include code, that should be flagged by the rule. If possible, the "correct" code
according to this new rule should also be demonstrated.
//Code to be flagged by the rule @isTest static void testNoRunAs() { Profile p = [SELECT Id FROM Profile WHERE Name='Standard User']; User u2 = new User(Alias = 'newUser', Email='newuser@testorg.com', EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', LocaleSidKey='en_US', ProfileId = p.Id, TimeZoneSidKey='America/Los_Angeles', UserName='newuser@testorg.com'); System.debug('Current User: ' + UserInfo.getUserName()); } //Code OK @isTest private class TestRunAs { public static testMethod void testIgnoreCase() { Profile p = [SELECT Id FROM Profile WHERE Name='Standard User']; User usr = new User(Alias = 'newUser', Email='newuser@testorg.com', EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', LocaleSidKey='en_US', ProfileId = p.Id, TimeZoneSidKey='America/Los_Angeles', UserName='newuser@testorg.com'); System.runAs(usr) { System.debug('Current User: ' + UserInfo.getUserName()); } } }
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4