ApexSensei

Drills › Prove it with tests

Build a test data factory

Prove it with tests · Intermediate · 12 min · Runs in your Salesforce Developer org · Apex Path

Scenario. Several service tests need Account records in different sizes without copying the same setup code.

Build a test data factory that inserts any number of Accounts with one DML statement.

What you will learn

A test data factory is a public @IsTest class with helpers that build records for many tests. A count parameter lets one helper make 1 record or 200.

List<Account> rows = AS_3C368617D776_DataFactory.createAccounts(3, 'north');

Gotcha. Put insert after the loop, not inside it. Inside the loop, 3 records cost 3 DML statements. After the loop, the whole list costs 1. A transaction allows 150.

The task

Finish the factory so it builds, inserts and returns the requested number of Accounts with one DML statement.

Examples:

  • createAccounts(3, 'north') → AS north-1, AS north-2, AS north-3, each with an Id
  • createAccounts(0, 'empty') → an empty list, with no error
  • 3 Accounts cost the same number of DML statements as 1 Account

Requirements:

  1. Return exactly count Accounts, in order.
  2. Name each one AS <token>-<n>, with n starting at 1.
  3. Insert the whole list once, after the loop, so every record has an Id.
  4. Keep createAccounts public static. The checks call it directly; your own test method is not graded.

Starter code

@IsTest
public class AS_3C368617D776_DataFactory {
    public static List<Account> createAccounts(Integer count, String token) {
        List<Account> records = new List<Account>();
        return records;
    }

    @IsTest
    static void createsThreeAccounts() {
        List<Account> records = createAccounts(3, 'visible');
        Assert.areEqual(3, records.size());
    }
}

When it passes

The factory returns count Accounts named AS <token>-1 onward, all inserted with one DML statement, and an empty list for zero.

Try this drill free

You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.

‹ Create isolated test data · Test success and exceptions ›