Wednesday 8 June 2011

Testing Trigger : Structure of Test Class for Apex Trigger


Test methods are essential part of any application developed in salesforce. To prepare a managed package all test methods should run successfully and total code coverage has to be more than 75% . but we should not prepare test methods for coverage of code but we should prepare them to ensure functionality. We should prepare test methods for positive and negative cases both. Where positive case is when correct input is given and received expected results and negative cases where we provide negative input and any validation if we have should get fired.  Properly written test methods also helps us in regression testing as well.
Before we start structure of testmethods first l would like to mention some basic points :
  • 1.       Independent of Org Data : Test methods do not commit any data to database. We should always write test methods creating all required data in the test method itself. No data dependency should be on org data. If we have any configuration settings also then we should also set there values in the test method to make test method execution independent of org data.
  • 2.       Use test.startTest and test.stopTest , all data creation should be done prior to using test.startTest. Limits do get reset as any webservice invoke or dml action gets executed after test.startTest
  • 3.       Always test for bulk data also if your code executed on bulk data as well.
  • 4.       Always assert your result in test method against expected result this will ensure you that your code is giving expected results.

Now we will start structuring a trigger class for a trigger


@isTest
private class testClass_Trigger{

    private static TestMethod void testTrigger(){
        
        //Step 1 : Data Insertion
        //Insert all the data required for your trigger according to your logic written in the trigger
        
        //Try to give unique values in fields while creating test data, like Name = 'TestAccountName' etc
        
        //If any configuration setting is also needed in your trigger insert that as well
        //If you create any configuration setting then you will need to create a user also so that mixed dml exception do not occur
        
        test.startTest();
        
        //If there are any static variables which are used in the trigger please set there values
        
        //Perform the dml action on which trigger gets fired , like insert, update ,delete , undelete
        
        //assert your results using system.assert and system.asserEquals 
        
        test.stopTest();
        // IF you have used any static variables
        
        
    }


}
Using above structure we can write test methods for a structure.

No comments:

Post a Comment

Tweet