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 }
NOTE
Class can be defined Public or Private.
Public generally for Test Data Factory
Test Method
Syntax:
@isTest static void method_name() { //content }
NOTE
No Parameter
Define method as a static void
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()); } }
NOTE:
System.assert - Check a condition of value TRUE and FALSE.
System.assertEquals - Test a value if the same or not.
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); } }