Test Helper class should contain most offen used code.

Classes for preparing database structure

Here is an example of myTestHelper class which has two methods; createAccount and createMyCustomObject.

public with sharing class myTestHelper {
    /* Account */
    public static Account createAccount(boolean makeInsert) {
        Account a = new Account();
        a.Name = 'testaccount ' + String.valueOf(Math.random()).substring(0,4);
        a.Phone = '+12 345 67 89';
        a.CurrencyIsoCode = 'EUR';
        a.Industry = 'Energy';
        a.BillingCountry = 'Netherlands';
        a.BillingPostalCode = '1321 RR';
        if (makeInsert) insert a;
        return a;
    /* my_CustomObject__c */
    public static my_CustomObject__c createMyCustomObject (boolean makeInsert) {
        Account a = createTestAccount(TRUE);
        my_CustomObject__c record = new my_CustomObject__c ();
        record.Account_Name__c = a.Id;
        record.quantity__c = 5; // Fill in all reqired fields to avoid errors when makeinsert = TRUE
        if (makeInsert) insert record;
        return record;

In createMyCustomObject i use record but you may use shortcut of your object name instead like mco for myCustomObject
With record name it is easier to copy paste and replace only object name when new object needs to be created.

How to use it

Create my_CustomObject__c with autogenerated account.

my_CustomObject__c mco = myTestHelper.createMyCustomObject(TRUE);

Create my_CustomObject__c with specific account;

Account a1 = createTestAccount(TRUE);
my_CustomObject__c mco = myTestHelper.createMyCustomObject(FALSE);
mco.Account_Name__c = a1.Id;
insert mco;




© Paweł Woźniak