Salesforce Platform dev 1 Apex trigger testing
Writing a test class for a trigger is equivalent to writing a test class for any apex class. Before you write a trigger you need to understand the working functionality of a trigger. In other words, what is triggering trigger is it before or after insert update.
Also, it is not a good practice to write complex logic within a trigger. Separate the logic to the new class so that testing becomes easier.
We are going to write a very basic trigger on contact object which will be before insert trigger and whose sole purpose is to append the last name with '-test' keyword.
Trigger Code
trigger ContactTrigger on Contact (before insert)
{
for(contact c : trigger.new)
{
c.lastname = c.lastname+'-test';
}
}
Test class
@istest
public class ContactTriggerTest
{
@istest static void TestContactTrigger()
{
system.Test.startTest();
contact c = new contact();
c.lastname= 'Porter beer';
insert c;
integer contactcount = [select count() from contact ];
system.assert(contactcount==1);
system.Test.stopTest();
}
}
Screenshot of code coverage of 100 per cent after the executing of a test class
Comments
Post a Comment