Test utility classes contain methods that can be called by test methods to perform useful tasks, such as setting up test data. Test utility classes are excluded from the org’s code size limit.

The following is an example of a test utility class. It takes two parameters: one for the number of accounts to create and one for the number of opportunities per account. It then returns these records for the purposes of testing. Notice that it predominately uses for loops and lists to achieve this.

public class TestDataFactory {
public static List createAccountsWithOpps(Integer numAccts, Integer numOppsPerAcct) {
List accts = new List();

for(Integer i=0;i<numAccts;i++) {
Account a = new Account(Name='TestAccount' + i);
insert accts;

List opps = new List();
for (Integer j=0;j<numAccts;j++) {
Account acct = accts[j];
// For each account just inserted, add opportunities
for (Integer k=0;k<numOppsPerAcct;k++) {
opps.add(new Opportunity(Name=acct.Name + ' Opportunity ' + k,
// Insert all opportunities for all accounts.
insert opps;

return accts;

Here we have a test which calls this test utility class:

private class TestAccountDeletion {
@isTest static void TestDeleteAccountWithOneOpportunity() {
// Test data setup
// Create one account with one opportunity by calling a utility method
Account[] accts = TestDataFactory.createAccountsWithOpps(1,1);

// Perform test
Database.DeleteResult result = Database.delete(accts[0], false);
// Verify that the deletion should have been stopped by the trigger,
// so check that we got back an error.
System.assert(result.getErrors().size() > 0);
System.assertEquals('Cannot delete account with related opportunities.',
Apex Testing Module Completed



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s