Test methods with full data access
Why is this an issue?
Using @IsTest(SeeAllData=true) allows test methods to access all data in the org, including production data. This creates several problems:
Non-deterministic tests: Tests may pass or fail depending on the org's data state.
Environment-specific failures: Tests that pass in one sandbox may fail in another or in production.
Unintended data modifications: Tests might accidentally modify real records.
Slower execution: Querying large datasets slows down test execution.
Examples
Example of incorrect code:
@IsTest(SeeAllData=true)
private class AccountServiceTest {
@IsTest
static void testGetAccounts() {
// Relies on existing org data
List<Account> accounts = AccountService.getAccounts();
Assert.isTrue(accounts.size() > 0);
}
}
Example of correct code:
@IsTest
private class AccountServiceTest {
@TestSetup
static void setupTestData() {
Account testAccount = TestDataFactory.createAccount('Test Account');
}
@IsTest
static void testGetAccounts() {
List<Account> accounts = AccountService.getAccounts();
Assert.areEqual(1, accounts.size());
}
}
How can I fix violations?
Remove
SeeAllData=true: Delete the annotation or set it tofalse.Create test data: Use
@TestSetupmethods or test data factories to create all required records.Use test data factories: Centralize test data creation in factory classes for reusability.
When should I disable this rule?
You may dismiss specific violations when testing functionality that requires access to data that cannot be created in tests, such as:
Standard objects that are not creatable via Apex
Records that require prior commits, like
FeedTrackedChangeor field history tracking records
Resources
