When you need to add a trigger to Salesforce, you will also have to write a test class. In addition to being a Development Best Practice, Salesforce requires that each trigger have at least 1 test class; and that the total test coverage of all your Apex code is at least 75%.
Unlike other Apex classes, you can’t add the test methods to the same file as the trigger. You need to create a separate Apex test class.
Here is the basic structure of a test class.
The @isTest attribute tells Salesforce that this is a test class, so:
- The Apex code is not included in the test coverage calculations
- When you deploy Apex code, the methods of this class will be run to generate code coverage
The testLeadInsert() method inserts a record which would cause an existing Lead trigger to fire. Notice that there is no direct reference to the trigger. All the test method needs to do is submit the appropriate record and event (insert, update, delete).
The System.AssertEquals() is the actual test line. In this example, it is confirming that when a Lead is inserted in the Open Status, the trigger has properly set the custom field DateOpened__c to the current date.
Your trigger test methods will be more complicated since you will need to make sure the conditions of your trigger are met. In this example, the Lead Status was set to ‘Open’. If my trigger was only looking for ‘Closed’ Leads, this test method would not be doing much testing. You can set as many fields as needed in your test methods. You can even create multiple records, of different objects to assemble the test data needed to confirm that your trigger is working correctly.
The records being inserted, updated, or deleted during test methods are not actually applied to your database, but they are processed as if they would be applied to the database so all triggers, validation rules, workflow rules and field updates are processed. This allows Salesforce to help you know that the code you are deploying into your Production org will not break existing functionality.