Sub topic 5
Test data isolation and @TestSetup
This chapter assumes you can write a basic @IsTest method, run SOQL and DML, and know the common governor limits. It covers how Apex keeps test data separate from your org's data, and how @TestSetup lets every test method in a class start from the same records.
Why tests are isolated
Apex tests run in a sandboxed transaction with two rules:
- No access to existing org data. By default, a test cannot see the Accounts, Contacts, or Opportunities already stored in the org. A query such as
SELECT COUNT() FROM Accountcounts only records the test or its setup method created. Setup objects such asUserandProfileare the exception. You can query those without creating them. - No permanent changes. Everything a test inserts, updates, or deletes is rolled back when the test method ends. Nothing is committed to the database, so you don't need cleanup code.
These rules give you two benefits. A test gives the same result in a sandbox, a scratch org, and production, because it doesn't depend on whatever records happen to exist there. Tests also can't damage real data.
The cost is that every test must create the records it needs. That is why this chapter matters. Without a plan, test classes fill up with repeated setup code.
@IsTest
private class IsolationDemoTest {
@IsTest
static void startsWithNoAccounts() {
Integer before = [SELECT COUNT() FROM Account];
Assert.areEqual(0, before, 'A test starts with no visible Account records');
insert new Account(Name = 'Temporary');
Assert.areEqual(1, [SELECT COUNT() FROM Account], 'The test can see its own record');
}
}The second assertion passes inside the test. After the method finishes, the platform rolls the insert back.
Creating data inside each method
The simplest approach is to build records at the top of each test method. It keeps the test self-contained, and a reader sees the data next to the assertions. For small classes this is fine.
Problems appear as the class grows. If ten tests all need the same three Accounts and their Contacts, you repeat the insert code ten times. You also run the same DML ten times, which slows the whole suite. @TestSetup addresses both problems.
How @TestSetup works
A method annotated with @TestSetup runs once, before any test method in the class. Records it creates are available to every test method. Each test method gets a fresh copy of that data, because the platform rolls back whatever a test method changed.
@IsTest
private class AccountIsolationTest {
@TestSetup
static void makeData() {
insert new Account(Name = 'Setup Account', Rating = 'Cold');
}
@IsTest
static void firstTestChangesTheRecord() {
Account a = [SELECT Id, Rating FROM Account WHERE Name = 'Setup Account'];
a.Rating = 'Hot';
update a;
Account reloaded = [SELECT Rating FROM Account WHERE Id = :a.Id];
Assert.areEqual('Hot', reloaded.Rating, 'The update should be visible in this test');
}
@IsTest
static void secondTestSeesTheOriginalRecord() {
Account a = [SELECT Id, Rating FROM Account WHERE Name = 'Setup Account'];
Assert.areEqual('Cold', a.Rating, 'Changes from other test methods must not leak');
}
}Whichever test runs first, the other still sees Cold. You can't rely on test method order, and with this design you don't need to.
Rules for @TestSetup methods
- A class can have only one
@TestSetupmethod. - The method must be
static, returnvoid, and take no parameters. - It can't be used in a class or method that has
@IsTest(SeeAllData=true). - If the setup method throws an exception, every test method in the class fails.
- Variables set in the setup method are not available in test methods. Static fields don't carry over either. The records are, so you must query them again.
Getting the records back
Because variables don't carry over, each test queries what it needs. Use a stable field such as Name to find the record. Don't rely on the order of results.
@IsTest
static void findsSetupAccountsByName() {
Account a = [SELECT Id, Name FROM Account WHERE Name = 'Setup Account' LIMIT 1];
Assert.isNotNull(a.Id, 'The setup record should be queryable');
}If a query returns no rows, [SELECT ... ] assigned to a single sObject throws QueryException. That usually means the setup method didn't create what the test expects, or the filter is wrong.
Governor limits and setup methods
The setup method runs in its own context. DML statements, SOQL queries, and CPU time it uses don't count against the limits of the test methods. So you can create a lot of data in setup and each test still starts with a clean allowance.
A test method can also reset limits inside itself by wrapping the code under test in Test.startTest() and Test.stopTest(). The next chapters of this tutorial cover that. Setup data is committed to the test's world before startTest, so it doesn't consume the limits of the code you are measuring.
Comparing the options
| Approach | Data source | Speed | Risk |
|---|---|---|---|
| Create in each test method | Inserted per test | Slower when many tests repeat the same inserts | Duplicated code |
| `@TestSetup` | Inserted once, then restored per test | Faster for shared data | Tests become coupled to the shared data |
| `@IsTest(SeeAllData=true)` | The real org's records | Depends on the org | Results change with org data |
A few records have special handling. For example, Test.getStandardPricebookId() returns the standard price book ID without SeeAllData. Check the documentation for such exceptions before you reach for SeeAllData.
Mixed DML errors
Salesforce separates setup objects, such as User, Group, and PermissionSetAssignment, from non-setup objects, such as Account. Inserting both kinds in the same transaction raises MIXED_DML_OPERATION. This often hits @TestSetup methods that create a user and then a record owned by that user.
The fix is to run the setup-object DML inside System.runAs. That block runs in its own context.
@IsTest
private class OwnedAccountTest {
@TestSetup
static void makeData() {
Profile p = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1];
User owner = new User(
Alias = 'owner1',
Email = '[email protected]',
EmailEncodingKey = 'UTF-8',
LastName = 'Owner',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = p.Id,
TimeZoneSidKey = 'America/Los_Angeles',
UserName = 'owner1' + System.currentTimeMillis() + '@example.com'
);
System.runAs(new User(Id = UserInfo.getUserId())) {
insert owner;
}
insert new Account(Name = 'Owned Account', OwnerId = owner.Id);
}
@IsTest
static void accountIsOwnedByTheSetupUser() {
Account a = [SELECT OwnerId FROM Account WHERE Name = 'Owned Account'];
User owner = [SELECT Id FROM User WHERE LastName = 'Owner' LIMIT 1];
Assert.areEqual(owner.Id, a.OwnerId, 'The account should belong to the setup user');
}
}The UserName must be unique across all of Salesforce, which is why the example appends the current time in milliseconds.
Keeping shared data safe
Shared setup data makes tests faster, but it can make them fragile. Follow these habits:
- Keep setup data minimal. Create only what most tests need. A test that needs unusual data should create it itself.
- Don't assert on totals that depend on other tests' needs. If someone adds a second Account to the setup method,
Assert.areEqual(1, [SELECT COUNT() FROM Account])breaks in unrelated tests. Filter by a known name instead. - Give records recognizable names. Names such as
Setup Accountmake queries and failure messages easy to read. - Don't rely on test order. Each test must pass when run alone.
- Move repeated record construction into a helper. A test data factory is a class with static methods that build records. That is the next chapter's topic.
Common mistakes
- Expecting variables from setup. A
static Account shared;assigned in the setup method isnullin test methods. Query the record instead. - Querying org data by accident. A query that works in a developer sandbox with real data but returns nothing in a test is a sign you were depending on org data. Create the record in the test.
- Two setup methods. Only one
@TestSetupis allowed. Put everything in one method and split it into helper methods. - Assuming setup data survives a change. If a test deletes the setup Account, the next test still sees it again. That is correct behavior, not a bug.
Exercise
A test class has a @TestSetup method that inserts one Account named 'Base'. Test method A updates its Rating to 'Hot'. Test method B runs afterward and queries the same Account. What Rating does B see, and why? What happens if B runs first?
Show answer
B sees the original Rating, not 'Hot'. The platform rolls back each test method's changes, and every test method starts with a fresh copy of the setup data. The order doesn't matter: if B runs first, it still sees the original value, and A's update happens only inside A's own transaction.
Exercise
A @TestSetup method inserts a User and then an Account in the same method, and the class fails with MIXEDDMLOPERATION. How do you fix it, and why does the fix work?
Show answer
Wrap the User insert in System.runAs(new User(Id = UserInfo.getUserId())) { insert u; }, then insert the Account outside the block. The runAs block runs in its own context, so setup-object DML and non-setup DML no longer share one transaction.