Unit Testing in Salesforce Apex
Notes on things to remember when writing unit tests for Apex on the Salesforce platform.
Test Data
- You can include a CSV of data as a
StaticResource, and then load it into unit tests really simply:- Important: Trailhead mentioned to set the Static Resource Cache Control to
Publicwhen creating the Static Resource
- Important: Trailhead mentioned to set the Static Resource Cache Control to
@IsTest
private class CSV_Tests {
@TestSetup
static void loadTestDataFromStaticResource(){
// NOTE: Assumes that we have created a Static Resource CSV file called accountData
List<sObject> accounts = Test.loadData(Account.SObjectType, 'accountData');
}
@IsTest
static void testLoadAccountsFromStaticResource() {
List<Account> accts = [SELECT Id FROM Account];
System.assert(accts.size() == 3, 'expected 3 accounts');
}
}
Test.startTest() & Test.stopTest()
Test.startTest()resets governor limits and isolates your test from test setupTest.stopTest()forces any asynchronous code to complete
Permission-based Testing
- Best to think in terms of Permission Sets more often than not
- This is something that I don’t ever do, but would be incredibly beneficial to test.
- Steps for Permission Set testing
- Generate (or load) Test Data
- Create fake user
- Assign that user to the previously-created permission set
- Call
Test.startTest() - Call
System.runAs(user) - Perform positive || negative test
- Code example testing that users without the correct Permission Set cannot see records:
- Note that the query doesn’t throw an exception; rather, no records are returned
@IsTest
private class PermissionsTests {
@TestSetup
static void testSetup(){
Account a = TestFactory.getAccount('No view For You!', true);
// NOTE: In this case we have a custom object that has a Private Sharing model
Private_Object__c po = new Private_Object__c(account__c = a.id, notes__c = 'foo');
insert po;
}
@IsTest
static void negativePermissionSetTest() {
User u = new User(
ProfileId = [SELECT Id FROM Profile WHERE Name = 'Standard User'].Id,
LastName = 'last',
Email = 'Cpt.Awesome@awesomesauce.com',
UserName = 'Cpt.Awesome.' + DateTime.now().getTime() + '@awesomesauce.com',
Alias = 'alias',
TimeZoneSidKey = 'America/Los_Angeles',
EmailEncodingKey = 'UTF-8',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US'
);
System.runAs(u){
Private_Object__c[] pos;
Test.startTest();
pos = [SELECT Id, Account__c, notes__c FROM Private_Object__c];
Test.stopTest();
System.assert(pos.size() == 0, 'a user without the permission set cannot see any records');
}
}
}