Apex Testing

Summary

This post will cover topics below:

  • Test Class
  • Test method
  • Test Data Factory

Introduction

Apex testing is crucial and mandatory to have in order to deploy  Apex in the Production environment. An overall score of apex testing is 75%, however, as best practices,  aims to have a higher score such as 100%.

Test class

Syntax:


@isTest
public class apexTestClass {
//contents
}

Test Method

Syntax:


@isTest
static void method_name() {
    //content
}

Example:


@isTest private class TestAcctDeletion {
    @isTest static void testDeleteAccount() {
        Account acct = new Account(Name='Test Acct');
        insert acct;
        
        Test.startTest();
        Database.deleteResult res = Database.deleteResult(acct, false);
        Test.stopTest();
        
        System.assert(res.isSuccess());
        System.assertEquals(true, res.isSuccess());
    }
}

Test Data Factory

A class to generate data in the Apex Test. 

Syntax:


@isTest public class TestDataFactory {
    public static createData() {
        //contents
    }
}

Example:


@isTest public class TestDataFactory {
    public static List createAccWithOpps(Integer numAccts, Integer numOpp) {
        List<Account> accts = new List<Account>();
        for(Integer i = 0; i < numAccts; i++) {
            Account a = new Account(Name='Test acct ' +i);
            accts.add(a);
        }
        insert accts;
        List<Opportunity> oppts = new List<Opportunity>();
        for(Integer i = 0; i < numAccts; i++) {
            Account acct = accts[i];
            for(Integer y = 0; y < numOpp; i++) {
                oppts.add(new Opportunity(Name=acct.Name+ 'Opp ' +y, StageName='Prospecting', AccountId=acct.Id));
            }
        }
        insert opps;
        return accts;
    }
}

Usage:


@isTest private class TestAcct {
    @isTest static void TestAcctWithOpp() {
        //create acct with TestDataFactory
        List<Account> accts = TestDataFactory.createAccWithOpps(1, 1);
    }
}

Leave a Reply