Applies to: Classic and Lightning |
A good best practice for developers is to have a helper class that builds test records. I’ve taken the best of what I’ve seen used throughout my consulting time and put them into a simple Salesforce Apex helper class.
A helper class that builds your test records is probably one of the most beneficial classes you can have in your toolbelt. It centralizes the rules around what it takes to create records.
Have you ever tried to deploy your code only to receive countless errors because a new validation rule was created and now none of your test classes are working? By moving the logic that creates records into a centralized class, provides one place to go to resolve the new rule. Without this, you’d have to visit every test class and make the fix over and over again.
Click to Tweet: I'm going to start using a testHelper class to create my test records in #Salesforce #TestClass Click To TweetThis code is not a plug and play piece of code. It’s a model to follow and you will need to make some adjustments.
The first has to do with Record Types. The createAccounts, createContacts and createCases methods all have logic to support Record Types. If you don’t have record types on those objects, you will need to comment out or delete those lines from your code.
The second is that I don’t include methods for which I don’t need. For example, if I don’t have any code that requires me to create Cases, then I’d either comment out the createCases method or delete it. Doing this will ensure all lines of this TestHelper class have code coverage.
The third step is to add any additional requirements needed to successfully create a record. If n phone number is required for all Accounts, then add:
r.Phone = '(515) 555-5555';
If email is required for Contacts, then add:
r.Email = 'test@test.com';
If you have a globalHelper or utilityHelper class, which I would also recommend, you move the getRecordTypeIdByName method to that class. This is a method you might find useful throughout your code. Perhaps I’ll create a post with several helper methods I’ve created over the years. These are nice to haves that help you segment your code into reusable chucks.
public with sharing class TestHelper {
// Returns Id of the record type for the supplied Object Name and Record Type Name.
public static Id getRecordTypeIdByName(String objName, String rTypeName) {
Id rId;
map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
if(gd.get(objName) != null) {
map<String, Schema.RecordTypeInfo> infos = gd.get(objName).getDescribe().getRecordTypeInfosByName();
rId = infos.get(rTypeName).getRecordTypeId();
}
return rId;
}
// use this method to create accounts in test classes
public static List<Account> createAccounts(string recordTypeName, Integer numberOfRecordsToCreate, Boolean insertRecords) {
string recTypeId;
if (recordTypeName <> null) recTypeId = getRecordTypeIdByName('Account', recordTypeName);
list<Account> records = new list<Account>();
for (Integer i=0; i < numberOfRecordsToCreate; i++) {
Account r = new Account ();
r.Name = 'TestName' + i;
// uncomment the next line, if you have account recordTypes
// if (recTypeId <> null) r.RecordTypeId = recTypeId;
records.add(r);
}
if(insertRecords) insert records;
return records;
}
// use this method to create contacts in test classes
public static List<Contact> createContacts(string recordTypeName, Integer numberOfRecordsToCreate, Boolean insertRecords) {
string recTypeId;
if (recordTypeName <> null) recTypeId = getRecordTypeIdByName('Contact', recordTypeName);
list<Contact> records = new list<Contact>();
for (Integer i=0; i < numberOfRecordsToCreate; i++) {
Contact r = new Contact ();
r.LastName = 'TestLastName' + i;
r.FirstName = 'TestFirstName' + i;
r.Email = 'email' + i + '@TestEmail' + i + '.com';
// uncomment the next line, if you have contact recordTypes
//if (recTypeId <> null) r.RecordTypeId = recTypeId;
records.add(r);
}
if(insertRecords) insert records;
return records;
}
}
We just mentioned the getRecordTypeIdByName method, but it does just what the name implies. If you pass in the Object Name and the Record Type Name (not the developer name), it will give you back the Record Type ID.
recTypeId = getRecordTypeIdByName('Account', 'Customer');
This is the createAccounts method and that’s what it does, it creates a list of Account records.
The first parameter you pass in is the Record Type Name. If you want to create ‘Customer’ records, then pass that in.
The second parameter tells the method how many records you want it to create. If you only need one record, the pass in 1. If you’re doing bulk testing, then perhaps you’ll want to pass in 500.
The third parameter tells the method if it should insert the new records or just return the list to you. If the default record creation does everything you need, then pass in TRUE. If you need to make some adjustments to the records, for your specific use case, then pass in FALSE. You’ll then want to commit the records after you’ve made any adjustments.
The sample call below, will insert four Customer and return them to a List:
List<Account> aList = TestHelper.createAccounts('Customer', 4, TRUE);
Your test method would then process as normal using these newly created account records. Remember, it returned the accounts in a List, so you may need to reference them as:
Account a1 = aList[0];
All the create methods follow this same basic premise. The parameters maybe be different and frankly, I’d recommend adjusting them to what works best for your needs.
Click to Tweet: I just learned a better way to create Test records #Salesforce #TestClass Click To TweetIf you look at the Create Opportunities method, on Line 65, you’ll see that I’m passing in my list of Accounts. This design will associate the new Opportunity records to the Accounts in my list. That might be helpful for you or it might not be.
The key to any Helper class is to follow a model that works for your needs and stick to it. It will make your code maintenance so much simpler. You do not need to rewrite all your existing test classes to begin using this. Just start the next time you need to create a new test method and then slowly move existing test classes over.
As always, if you need my assistance, please contact me here. I’m always happy to provide guidance to help you succeed.
Click to Tweet: Terry explained how to create Test records in a simple to understand way. #Salesforce #TestClass Click To Tweet