Activity Forums Salesforce® Discussions How to create utility class in salesforce?

  • Hariom Chaudhary

    Member
    September 11, 2019 at 11:27 am

    Hi,

    Common test utility classes are public test classes that contain reusable code for test data creation.
    Public test utility classes are defined with the isTest annotation, and as such, are excluded from the organisation code size limit and execute in test context. They can be called by test methods but not by non-test code.

    The methods in the public test utility class are defined the same way methods are in non-test classes. They can take parameters and can return a value. The methods should be declared as public or global to be visible to other test classes. These common methods can be called by any test method in your Apex classes to set up test data before running the test. While you can create public methods for test data creation in a regular Apex class, without the isTest annotation, you don’t get the benefit of excluding this code from the organisation code size limit.

    Example of utility class :

    @isTest
    public class TestDataFactory {
    public static void createTestRecords(Integer numAccts, Integer numContactsPerAcct) {
    List<Account> accts = new List<Account>();

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

    List<Contact> cons = new List<Contact>();
    for (Integer j=0;j<numAccts;j++) {
    Account acct = accts[j];
    // For each account just inserted, add contacts
    for (Integer k=numContactsPerAcct*j;k<numContactsPerAcct*(j+1);k++) {
    cons.add(new Contact(firstname='Test'+k,
    lastname='Test'+k,
    AccountId=acct.Id));
    }
    }
    // Insert all contacts for all accounts
    insert cons;
    }
    }

  • Saddam

    Member
    September 11, 2019 at 2:48 pm

    Hi Piyush,

    Utility classes are helper classes that consisits of reusable methods.
    From triggers we can call  methods in such public classes. This helps to reduce code with in trigger and make it more structured.
    If we have a trigger on oppotunity which does date format and assign it to a field value, it can be written as follows with the help of utilty class

    trigger updateOpp on Opportunity (before insert){
    for(Opportunity  opp : Trigger.new){
    opp.formattedDate__c = TriggerHelper.formatDate(opp.someDate__c);
    }
    }

    //Utility Class
    Public Class TriggerHelper{
    Public Static string formatDate(Date inputDate){
    return inputDate.format();
    }
    }

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos