DEV Community

Renuka Singh
Renuka Singh

Posted on

Salesforce Apex Test Data Factory: Write Cleaner and Reusable Unit Tests

Writing test classes is an important part of Salesforce development. However, creating test records separately in every test method can make code repetitive and difficult to maintain.

Apex Test Data Factory is a useful approach that helps developers create reusable test records. Instead of writing the same Account, Contact, or Opportunity creation logic repeatedly, you can keep it in one place and reuse it across multiple test classes.

In this article, we will explore how to build a simple test data factory and use it in Salesforce Apex tests.

Why Use a Test Data Factory?

Consider a Salesforce project where multiple test classes need Account and Contact records.

Without a reusable approach, every test class may contain similar code:

Account acc = new Account(Name = 'Test Account');
insert acc;

Contact con = new Contact(
FirstName = 'John',
LastName = 'Doe',
AccountId = acc.Id
);
insert con;

This works, but repeating the same logic across multiple test classes creates maintenance problems.

A test data factory helps by:

Reducing duplicate test setup code.

Making test classes easier to read.

Keeping test data creation consistent.

Simplifying changes to test records.

Supporting reusable test scenarios.

Step 1: Create a Test Data Factory Class

Start by creating an Apex class that contains methods for generating test records.

For example, create an Account factory:

@IsTest
public class TestDataFactory {

public static Account createAccount() {
    Account acc = new Account(
        Name = 'Test Business'
    );

    insert acc;
    return acc;
}
Enter fullscreen mode Exit fullscreen mode

}

This method creates an Account and returns the inserted record.

You can now call this method from different test classes.

Step 2: Add Contact Creation Logic

A Contact usually needs an associated Account.

You can add another method to the same factory:

@IsTest
public class TestDataFactory {

public static Account createAccount() {
    Account acc = new Account(
        Name = 'Test Business'
    );

    insert acc;
    return acc;
}

public static Contact createContact(Id accountId) {
    Contact con = new Contact(
        FirstName = 'John',
        LastName = 'Doe',
        AccountId = accountId
    );

    insert con;
    return con;
}
Enter fullscreen mode Exit fullscreen mode

}

Now, both Account and Contact records can be created using reusable methods.

Step 3: Use the Factory in an Apex Test Class

Let's use the factory in a simple test class.

@IsTest
private class ContactTest {

@IsTest
static void testContactCreation() {

    Account acc = TestDataFactory.createAccount();

    Contact con = TestDataFactory.createContact(acc.Id);

    System.assertEquals(acc.Id, con.AccountId);
    System.assertEquals('Doe', con.LastName);
}
Enter fullscreen mode Exit fullscreen mode

}

The test method is now shorter and easier to understand.

Instead of managing all the record creation logic inside the test, it simply calls the required factory methods.

Step 4: Support Multiple Test Scenarios

A useful factory should allow different test data instead of always creating identical records.

You can use method parameters to make the factory more flexible:

@IsTest
public class TestDataFactory {

public static Account createAccount(String accountName) {

    Account acc = new Account(
        Name = accountName
    );

    insert acc;
    return acc;
}
Enter fullscreen mode Exit fullscreen mode

}

Now you can create different Account records:

Account acc1 =
TestDataFactory.createAccount('Retail Company');

Account acc2 =
TestDataFactory.createAccount('Technology Company');

This approach is useful when testing different business conditions.

Step 5: Follow Good Test Data Factory Practices

A test data factory should make tests simpler, not introduce additional complexity.

Keep these practices in mind:

  1. Use meaningful method names

Names such as createAccount() and createContact() make the purpose clear.

  1. Avoid unnecessary hardcoded values

Use parameters when different test scenarios require different data.

  1. Keep methods focused

Each method should create a specific type of record or a clearly defined group of related records.

  1. Avoid depending on existing org data

Create the records your test needs. Use SeeAllData=true only when there is a specific reason, because tests should normally be isolated from existing business records.

  1. Consider bulk test data

For testing triggers and bulk operations, create multiple records in one operation rather than relying only on single-record factory methods.

Final Thoughts

Apex Test Data Factories help Salesforce developers write cleaner, reusable, and easier-to-maintain unit tests.

By moving repetitive record creation logic into a dedicated class, developers can focus more on testing business logic and less on preparing test records.

For Salesforce development, implementation, and technical guidance, you can also explore iBirds Software Services.

Top comments (0)