Monday, 7 November 2022

Behavior of Salesforce data in Apex tests

 1.Existing org data isn't visible to Apex tests.

2.As a best practice you should always create your own test data for each test.


Reasons to create your own test data :


1.Data unavailability

  your org might not have the data for both positive and negative tests.

2.Data inconsistency

  Data can be different between orgs and test runs.


Note : In some scenarios like testing report data or field history records 

        you might need to have access to our org data because you can't create 

         those records through apex.

       In those cases you can annotate your test class with 'seeAllData' is equal to true annotation.


  ex : @isTest(seeAllData=true)

       public class DemoCtrlTest{

          

          @isTest

          static void testAccountFilter(){

          

          }

       

       }  


3. Apex test data is transient and isn't committed to the database.


Note : which means the data is present only as long as your test is running.


4.Testsetup methods are helpful test setup methods are defined in a test class itself

   they take no arguments and no return a value.

   

   ex 

      @istest

      public class DemoCtrlTest{

      

      @testSetup 

       static void createTestData(){

         // create test data here

       }

      }


a. Test setup method is automatically executed first, before any test method.

b. Records created in the test setup method are accessible to all test methods.

c. Changes to records by a test method are rolled back before another test method is executed.

d. All records are rolled back after the test class finishes executing.


create test data using CSV file :


ex : @testSetup 

      static void creatTestData(){

        Test.loadData(Account.sobjectType,'Mock_Account_Data');

      }   


Test Data and Governor Limits :


Whenever a test class runs the test data creation and test execution both happens in the same transaction.   


ex : 

Test.startTest();

Test.stopTest();


The startTest() method marks the point in your test code where the test 

actually begins and stopTest() method marks the point where your test ends.


Any code that executes between these two methods is assigned a 'new set of governor limits '.

The code inside start and stop block has one set of limits and the code outside has another set of limits.

The code outside whether before or after that start and stop methods shares the same limit.


No comments:

Post a Comment