Test Data in APEX Test Classes
What Is Test Data?
Test data in Apex is the transient data that is not committed to the database and is created by each test class to test the Apex code functionality for which it is created. Using this transient test data makes it easy to test the functionality of other Apex classes and triggers.
- This does not change the data already in the system, nor is any cleanup required after testing is complete.
- Test classes can be moved to any environment and executed there as they create their own data; hence, they are environment or org-agnostic.
Ex:
trigger PositionTrigger on Position__c(before update) {
if (Trigger.isBefore && Trigger.isUpdate) {
PositionTriggerHandler.handleBeforeUpdate(Trigger.newMap, Trigger.oldMap);
}
}
Ex:
public class PositionTriggerHandler {
// static method called to handle the before update logic
public static void handleBeforeUpdate(Map < Id, Position__c > newMap, Map < Id, Position__c > oldMap) {
// Loop over all the position records being updated
for (Position__c pos: newMap.Values()) {
// Compare new Min Salary field value with old value
if (pos.Min_Salary__c < > oldMap.get(pos.Id).Min_Salary__c) {
// If old and new values are not the same, assign the old value to the comments field
pos.Comments__c = String.valueOf(oldMap.get(pos.Id).Min_Salary__c);
}
}
}
}
@isTest
public class PositionTriggerTest {
static testMethod void updateMinimumSalary() {
PositionTriggerTest.insertPositionRecord();
List < Position__c > positionListToUpdate = new List < Position__c > ();
for (Position__c pos: [Select Min_Salary__c from Position__c]) {
pos.Min_Salary__c = 30000;
positionListToUpdate.add(pos);
}
Test.startTest();
update positionListToUpdate;
Test.stopTest();
List < Position__c > posList = [Select Comments__c from Position__c];
system.assertEquals(posList[0].Comments__c, '20000');
}
static void insertPositionRecord() {
List < Position__c > positionListToInsert = new List < Position__c > ();
for (Integer i = 0; i < 100; i++) {
Position__c pos = new Position__c();
pos.Name = 'Salesforce Developer' + i;
pos.Min_Salary__c = 20000;
positionListToInsert.add(pos);
}
insert positionListToInsert;
}
}

Features Of isTest(SeeAllData=true) Annotation
By default, Salesforce org data is not visible to the test class; it must create its own data. However, this behaviour can be changed by annotating a Test class or test method with @isTest(SeeAllData=true) annotation, which opens up the entire org’s data to the test class.
Characteristics of the IsTest(SeeAllData=true) Annotation are:
- If this annotation is defined at the Class level, it is automatically applied to all its test methods. This annotation can also be used individually at the method level.
- If the annotation is applied on the class level, then using isTest(SeeAllData=false) on a particular method does not restrict its access to the org’s data.
Accessing Standard Price Book in Test Classes
- Use the Test.getStandardPricebookId() method to fetch the standard price book ID in the Test Class.
- No need to write a SOQL query.
- No need to use the SeeAllData annotation.
Ex:
@isTest
public class PriceBookTest {
// Utility method that can be called by Apex tests to create price book entries. static testmethod void addPricebookEntries() {
// First, set up test price book entries.
// Insert a test product.
Product2 prod = new Product2(Name = 'Laptop X200', Family = 'Hardware');
insert prod;
// Get standard price book ID.
// This is available irrespective of the state of SeeAllData.
Id pricebookId = Test.getStandardPricebookId();
// 1. Insert a price book entry for the standard price book.
// Standard price book entries require the standard price book ID we got earlier.
PricebookEntry standardPrice = new PricebookEntry(Pricebook2Id = pricebookId, Product2Id = prod.Id, UnitPrice = 10000, IsActive = true);
insert standardPrice;
} // closes addPricebookEntries()
} // closes PriceBookTest class
Steps To Load Test Data
To load test data in Apex in a test class without writing much code, follow these three steps:
- Create the data you want to load into a .csv file.
- Create a static resource and upload the .csv file to it.
- Call Test.loadData in your test method.
Syntax:
List<sObject> ls = Test.loadData(Position__c.sObjectType, 'positionResource');
Loading Test Data—Example:
Here is an example of loading Position object data via the Test.loadData method. Static Resource name is “positionResource,” and Test Class is “PositionTriggerTest”.
test.loadData apex example:
Ex:
@isTest
public class PositionTriggerTest {
static testMethod void updateMinimumSalary() {
// Load the test accounts from the static resource
List < sObject > positionLoadRecordList = Test.loadData(Position__c.sObjectType, 'positionResource');
// Verify that all 9 test position records were created
System.assertEquals(positionLoadRecordList.size(), 9);
List < Position__c > positionListToUpdate = new List < Position__c > ();
for (Position__c pos: [SELECT Min_Salary__c FROM Position__c]) {
pos.Min_Salary__c = 30000;
positionListToUpdate.add(pos);
}
Test.startTest();
update positionListToUpdate;
Test.stopTest();
}
}

Test Setup Methods
These are Special methods used to create test data in Salesforce Apex that is accessible to the entire Test Class. These methods use the @TestSetup annotation.
testsetup method apex example:
Ex:
@isTest
private class CommonTestSetup {
@testSetup static void setup() {
// Create common test accounts
List < Account > testAccts = new List < Account > ();
for (Integer i = 0; i < 2; i++) {
testAccts.add(new Account(Name = 'TestAcct' + i));
}
insert testAccts;
}
@isTest static void testMethod1() {
// Get the first test account by using a SOQL query
Account acct = [SELECT Id FROM Account WHERE Name = 'TestAcct0'
LIMIT 1
]; // Modify first account
acct.Phone = '555-1212';
// This update is local to this test method only.
update acct;
// Delete second account
Account acct2 = [SELECT Id FROM Account WHERE Name = 'TestAcct1'
LIMIT 1
]; // This deletion is local to this test method only.
delete acct2;
}
Next Chapter
Need more support?
Get a head start with our FREE study notes!
Learn more and get all the answers you need at zero cost. Improve your skills using our detailed notes prepared by industry experts to help you excel.