Missing data factory in test methods
Why is this an issue?
Creating test records directly in test methods leads to maintenance problems:
Validation rule changes break tests: When validation rules are added or modified, all tests that create records inline may fail.
Code duplication: The same record creation logic is repeated across multiple test methods.
Inconsistent test data: Different tests may create records with different field values, leading to inconsistent behavior.
Centralizing test data creation in factory classes makes tests more maintainable and resilient to schema changes. Note that @TestSetup methods are not flagged by this rule, as they are already a centralized place for test data creation.
Examples
Example of incorrect code:
@IsTest
static void testAccountProcessing() {
Account acc = new Account(
Name = 'Test Account',
Industry = 'Technology',
BillingStreet = '123 Main St',
BillingCity = 'San Francisco'
);
insert acc;
// Test logic...
}
Example of correct code using a test data factory:
// TestDataFactory.cls
@IsTest
public class TestDataFactory {
public static Account createAccount(String name) {
Account acc = new Account(
Name = name,
Industry = 'Technology',
BillingStreet = '123 Main St',
BillingCity = 'San Francisco'
);
insert acc;
return acc;
}
}
// Test class
@IsTest
static void testAccountProcessing() {
Account acc = TestDataFactory.createAccount('Test Account');
// Test logic...
}
How can I fix violations?
Create a test data factory class: Build a centralized class with methods for creating common test records.
Handle required fields in one place: Include all required fields and validation rule requirements in the factory.
Use method parameters for variations: Allow callers to specify values that vary between tests while defaulting others.
When should I disable this rule?
You may dismiss specific violations for:
Simple test classes with only one or two test methods
Tests for utility classes that don't involve SObjects
Resources
