Free Salesforce Developers Tutorials >

Chapter 11 - Apex Testing >

Test Data in APEX Test Classes

Test Data in APEX Test Classes

What You’ll Learn


S2 Labs

What Is Test Data?

Test data 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. The use of 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 has been finished. 
  • 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);
    }
}
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 same, assign old value to 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;
    }
}

Salesforce Developer Training

Features Of isTest(SeeAllData=true) Annotation

By default, Salesforce org’s data is not visible to the test class, rather it has to create its own data. However, this behaviour can be changed by annotating a Test class or test method with @isTest(SeeAllData=true) annotation opens up the entire org’s data to the test class.

Characteristics of the IsTest(SeeAllData=true) Annotation are:

  • If this annotation is defined on the Class level, then this annotation 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.

Features Of isTest(SeeAllData=true) Annotation

  • Use Test.getStandardPricebookId() method to fetch the standard price book id in Test Class. 
  • No need to write a SOQL query.
  • No need to use 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;
}

Steps To Load Test Data

To load data in a test class without writing many codes, follow these three steps:

  • Create data you want to load in a .csv file.
  • Create a static resource and upload the .csv file in 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 for Position object data load via Test.loadData method. Static Resource name is “positionResource” and Test Class is “PositionTriggerTest”.

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();
    }
}

Salesforce Training

Test Setup Methods

These are Special methods which are used to create test data that becomes accessible to the whole Test Class.

These methods use @TestSetup annotation.

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;
    }

Download Study Material

Get access to exclusive study material for Salesforce Certification and ace your exams!

Download Now

Our Salesforce Certification Courses

Hey there! Glad you made it through our Salesforce Developer Training for beginners . But wait! We've got some high-in-demand Salesforce courses for you to take your Salesforce skills to the next level, making you a desired professional in the Salesforce job market.

Post a Comment

Your email address will not be published. Required fields are marked *