Salesforce Test Utility Classes | TestDataFactory | Util Test in salesforce

Test utility classes are public test classes that contain reusable code for test data creation.

The TestDataFactory/ TestUtility class is a special type of class —

It is a public class that is annotated with @isTestand as such, are excluded from the organization code size limit and execute in test thisContext and can be accessed only from a running test.

https://sfdclessonsandknowledge.wordpress.com/category/apex-lessons/

Step 1:- Create TestDataFactory / Test utility
@isTest
public with sharing class TestDataFactory 
{ /* This method is test data for create thisAccount */
      public static thisAccount createthisAccount(Boolean doInsert)
      {        
               thisAccount thisAcc = new thisAccount();
               thisAcc.Name = ‘Test thisAccount’;        

                if(doInsert){
                       insert thisAcc;
                }
                return thisAcc;
       }
}

Step 2:- How to Use TestDataFactory / Test utility
@isTest
private class MyTestClass 
{
          static testmethod void myUnitTest() 
          {
             Account thisAccObj = TestDataFactory.createthisAccount(true);
          }

          // If you want to edit data according to apex class then try like below

          static testmethod void myUnitTest1() 
          { 
            thisAccount thisAccObj = TestDataFactory.createthisAccount(false);
            thisAccObj.Name =’MyName’;
            insert thisAccObj;
         }
}