Advanced 25 min read

Creating Test Data

By the end of this lesson, you'll be able to:

  • Explain why each test needs its own fresh data, not shared production data
  • Insert test sObjects inside a test method
  • Recognize the automatic test-data isolation Salesforce provides

Prerequisites: "Your First Test Class"

Tests never see real org data

@isTest
static void testSomething() {
    List<Account> accounts = [SELECT Id FROM Account]; // returns EMPTY, even in a full production org
}

By design, Salesforce automatically isolates every test's data — a query inside a test method never sees real, existing records, even if the org has millions of Account records. This is a deliberate safety guarantee: tests can never accidentally read or corrupt real production data, and different test methods never interfere with each other's data either.

Creating the data each test needs

@isTest
private class EmployeeDirectoryTest {
    @isTest
    static void addEmployeeStoresTheRecord() {
        EmployeeDirectory directory = new EmployeeDirectory();
        Employee emp = new Employee('E001', 'Amara Nkosi', 'amara@example.com');

        Boolean added = directory.addEmployee(emp);

        System.assertEquals(true, added);
        System.assertEquals(1, directory.getEmployeeCount());
    }
}

Since Employee and EmployeeDirectory (Module 17) are plain Apex classes, not sObjects, this test just creates them directly with new — no DML or SOQL involved at all. Tests against real sObjects need actual insert statements, covered next.

Inserting sObject test data

@isTest
private class LibraryServiceTest {
    @isTest
    static void addBookInsertsARecord() {
        LibraryService library = new LibraryService();

        Book__c book = library.addBook('The Long Walk', 'Richard Bachman', '978-0-451-14098-6');

        System.assertNotEquals(null, book.Id);

        List<Book__c> allBooks = [SELECT Id, Title__c FROM Book__c];
        System.assertEquals(1, allBooks.size());
    }
}

library.addBook(...) performs a real insert (Module 22) — and because tests run in their own isolated data, the follow-up query confidently finds exactly the one book this test itself created, never any leftover data from another test or from production.

Exercise

Write a test method that inserts an Account with a Name, then queries it back and asserts the Name matches.

Show hint

insert acc; then re-query by Id and assertEquals on the Name.

APEX

Creating Test Data Quiz

1. What data does a SOQL query inside a test method see?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

Every test runs against a completely empty, isolated copy of the org's data — meaning every test method must create whatever records it needs itself, and nothing it inserts ever touches real data.