Sub topic 7
Creating test data: factories, @TestSetup and avoiding SeeAllData
This chapter assumes you can write a basic Apex test class with @isTest methods and the Assert class. It also assumes you know SOQL, DML and the idea of a governor limit. Here you will learn where test data should come from and how to keep each test independent of the org it runs in.
Why tests must own their data
A test that depends on records already in the org is fragile. It passes in the sandbox where someone created the right Account, then fails in a scratch org or in production, where that Account does not exist. It can also fail later when someone edits the record it relied on.
Salesforce pushes you toward self-contained tests. Since API version 24, a test method cannot see the org's existing records by default. Your test queries return only the records the test created itself. Some metadata-like objects are still visible, including User, Profile, RecordType, Organization and AsyncApexJob.
This default is useful. A test that creates all of its own data behaves the same in every org, and every record it creates is rolled back when the test finishes. No test data stays behind.
Creating records directly in a test
The simplest approach is to build records inside the test method:
@isTest
private class SimpleDataTest {
@isTest
static void accountIsSaved() {
Account a = new Account(Name = 'Direct Account');
insert a;
Assert.isNotNull(a.Id, 'Insert should assign an Id');
}
}This is fine for one record in one test. It becomes a problem when twenty tests each repeat the same five lines. A new required field or validation rule then forces you to edit twenty places. Two tools solve this: a test data factory and @TestSetup.
A test data factory
A test data factory is a class of static methods that return valid records. Tests call the factory instead of constructing records by hand. When a validation rule changes, you fix the factory once.
@isTest
public class TestDataFactory {
public static List<Account> createAccounts(Integer count, Boolean doInsert) {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < count; i++) {
accounts.add(new Account(
Name = 'Factory Account ' + i,
AnnualRevenue = 1000
));
}
if (doInsert) {
insert accounts;
}
return accounts;
}
public static List<Contact> createContacts(
List<Account> accounts, Integer perAccount, Boolean doInsert
) {
List<Contact> contacts = new List<Contact>();
for (Account a : accounts) {
for (Integer i = 0; i < perAccount; i++) {
contacts.add(new Contact(
LastName = 'Contact ' + i,
AccountId = a.Id
));
}
}
if (doInsert) {
insert contacts;
}
return contacts;
}
}Several design choices matter here:
@isTeston the class. Apex in a class marked@isTestdoes not count against the org's Apex code size limit, and it is not included in coverage totals. A public method in such a class can only be called from test context.- A
doInsertflag. Sometimes a test needs to change a field before inserting. WithdoInsert = falsethe test gets the unsaved records, changes them, and inserts them itself. - A count parameter. The same method builds one record for a simple test or 200 for a bulk test.
- Unique values. The loop index in
Nameavoids collisions when a unique field or duplicate rule exists. - Valid by default. The factory sets every field the org requires. Tests then override only the field they care about.
Keep factories free of assertions and business logic. Their only job is to produce valid records.
Sharing data with @TestSetup
A method annotated with @TestSetup runs once before the test methods in the class. Every test method then sees the records it created. Each test method gets its own copy of that data, because Apex rolls back any changes a test method makes before the next one starts.
@isTest
private class AccountContactTest {
@TestSetup
static void makeData() {
List<Account> accounts = TestDataFactory.createAccounts(2, true);
TestDataFactory.createContacts(accounts, 3, true);
}
@isTest
static void setupDataIsVisible() {
Assert.areEqual(2, [SELECT COUNT() FROM Account], 'Two accounts from setup');
Assert.areEqual(6, [SELECT COUNT() FROM Contact], 'Three contacts per account');
}
@isTest
static void deletingContactsStaysInsideThisTest() {
delete [SELECT Id FROM Contact];
Assert.areEqual(0, [SELECT COUNT() FROM Contact], 'Deleted in this test');
}
@isTest
static void otherTestsStillSeeAllContacts() {
Assert.areEqual(6, [SELECT COUNT() FROM Contact], 'Rollback restores the data');
}
}The three methods can run in any order, and otherTestsStillSeeAllContacts still passes. The delete in the second method is undone.
Rules and behavior of @TestSetup
- A class can have only one
@TestSetupmethod. It must bestatic, returnvoidand take no parameters. - The test method does not receive the records as variables. It must query them, as the example does. Query by a stable value such as a name, not by position.
- If the setup method throws an exception or fails a DML statement, every test in the class fails.
- The setup method does not run again for each test method, so it saves DML statements and CPU time compared with repeating the same inserts. Governor limits are counted separately for the setup method and for each test method.
@TestSetupis not supported in a class marked@isTest(SeeAllData=true).
Use @TestSetup for data that most or all tests in the class share. If only one test needs a particular record, create it inside that test. A large setup method that every test pays for makes the class slower and hides what each test depends on.
Avoiding SeeAllData
@isTest(SeeAllData=true) turns off data isolation, so the test can query every record in the org. Avoid it. A test using it can pass in one org and fail in another. It can also fail when someone deletes a record, and it can behave differently depending on how much data exists.
// Avoid this unless there is no alternative
@isTest(SeeAllData=true)
private class FragileTest {
@isTest
static void dependsOnOrgData() {
Account a = [SELECT Id FROM Account WHERE Name = 'Acme' LIMIT 1];
Assert.isNotNull(a);
}
}This test fails with a QueryException in any org that has no Account named Acme. The SeeAllData setting also applies at the class level to every method in the class, so one method that needs it exposes all of them.
Most reasons people give for needing SeeAllData have a better answer:
| Situation | Better approach |
|---|---|
| The code reads a standard record such as the standard price book | Call `Test.getStandardPricebookId()` |
| The test needs a user with a certain profile | Query the `Profile`, create a `User` in the test |
| The test needs many realistic records | Load them from a static resource with `Test.loadData()` |
| The code reads custom metadata or custom settings | Custom metadata records are visible to tests, and custom settings can be created in the test |
Some APIs still require SeeAllData=true, such as certain ConnectApi methods. If you must use it, put those tests in their own small class so the other tests keep their isolation.
Setup objects and mixed DML
Some objects, called setup objects, configure the org rather than hold business data. Examples are User, Group and PermissionSet. Inserting a setup object and a non-setup object (such as an Account) in the same transaction raises MIXED_DML_OPERATION.
The usual fix is to run one of the operations inside System.runAs, which starts a separate context:
@isTest
private class MixedDmlTest {
@isTest
static void createsUserAndAccount() {
Profile p = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1];
User u = new User(
Alias = 'tuser',
Email = '[email protected]',
EmailEncodingKey = 'UTF-8',
LastName = 'Tester',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = p.Id,
TimeZoneSidKey = 'America/Los_Angeles',
UserName = 'tuser' + System.currentTimeMillis() + '@example.com'
);
insert u;
System.runAs(u) {
insert new Account(Name = 'Owned by tester');
}
Assert.areEqual(1, [SELECT COUNT() FROM Account WHERE OwnerId = :u.Id]);
}
}The user name includes the current time because user names must be unique across all of Salesforce. A later chapter covers System.runAs in full.
Common mistakes
- Relying on record order. Without
ORDER BY, SOQL does not guarantee order. Query by a field you set. - Assuming setup data survives a change. A test's inserts, updates and deletes disappear after the test method, so one test cannot prepare data for another.
- Hard-coded IDs. Record IDs differ between orgs. Never put one in a test.
- A factory that goes stale. When a new required field or validation rule breaks the factory, every test fails at once. That is a signal to fix the factory, not to work around it in each test.
- Hidden data in setup. If a test asserts on a count, make sure it is clear which records came from setup and which the test added.
Exercise
A class has a @TestSetup method that inserts 5 Accounts. Test method A deletes all Accounts. Test method B asserts that 5 Accounts exist. B runs after A. Does B pass, and why?
Show answer
B passes. Each test method starts from the data the setup method created, because Apex rolls back the changes a test method makes before the next one runs. The delete in A has no effect on B, so the order of the methods does not matter.
Exercise
Why does a factory method usually take a doInsert flag, and why is the factory class marked @isTest?
Show answer
The flag lets a test receive unsaved records, change a field, and insert them itself, while other tests can get saved records in one call. The @isTest annotation keeps the factory out of the org's Apex code size limit and out of coverage totals, and it makes the class callable only from test context.