Test Class For Trigger | Part 1 | Salesforce

























Test Class For Apex Trigger


In previous EPISODE we discussed the basics of how and when to write test classes. Where we learnt the syntax and the useful keyword while writing the test classes.

From this episode, you will learn how to write test classes for triggers in detail. As well as in the upcoming episode you will learn about how to write test classes for a different type of apex codes.

So Let's get started Kid......#JourneyToTestClasses

Why you will write the test class for apex trigger in salesforce ?

Let's consider, you have a trigger written by you or someone else then following things you must know before writing the test class for this trigger :

1. Functionality of trigger
2. When a trigger is executing
3. Conditions/Criteria written inside the apex triggers
4. Positive and negative scenarios in which your trigger will execute and will not execute.

Above points are very important to know before writing test classes for your trigger.

NOTE: If you don't know the functionality of code then first try to understand the code and above 4 points before stating anything.

Now we will consider some scenario-based questions of triggers and then we will write the trigger for that. Please try to understand and try to find out the answers of above 4 Points.

Scenario 1 :
When we are trying to insert the record into an object If there is any record existing with the same account name it should prevent duplicate record.

Trigger :
============================================
trigger accounInsert on Account(before insert)
{
//Check for all the new account record in for loop
 for(Account a : Trigger.New)
 {
//Query
  List<Account> mynew = [SELECT Id, Name FROM Account WHERE                                                      Name= :a.Name];
  if(mynew.size() > 0)
  {
//Add Error message if there is record after querying 
   a.Name.addError('Account with name is existing'); 
  }
 }
}
============================================

Now let's try to write test class of the same salesforce apex trigger written above.

Test Class :
============================================
@isTest //Annotation so that salesforce can undertand this is test class
public class AccountInsert
{
//Defind testmethod keyword while defining method 
 public static testMethod void testInsert()
 {
//Defind variables
  String addError;
  String myname = 'SalesforceKid';
//Create an instance of an object on which you want to check this trigger is working or not. 
  Account a2 = new Account(name = myname);
//Query 
  List<Account> x =[SELECT Id, Name FROM Account WHERE Name=                                         :myname];
 if(x.size() < 1)
  {
//Check if list is empty  
   System.assertEquals(0, x.size());
//Insert the record
   Insert a2;
  }
else
 {
//Otherwise show error if there is something in the list with same name
  addError ='Existing';
  }
//Check whether the error you are getting is similar to the one you added
System.assertEquals('Existing', addError);
 }
}
============================================

Coool Right 😎 ?? Quite easy when you breakdown the code first and try to replicate the same functionality inside your test class.

Now let's consider another scenario where we can learn test classes for a trigger once again

Scenario 2 :
Write a trigger to prefix Account Name with 'Mr.' whenever a new record is inserted.

Trigger :
============================================
trigger accountprefix on Account(before insert)
{
//for every new account
 for(Account a : Trigger.New)
 {
//append 'Mr.' with every account name 
  a.Name = 'Mr.' + a.Name;
 }
}
============================================

Now let's try again to write test class of the same salesforce apex trigger written above.

Test Class :
============================================
@isTest //Annotation of test class
public class AccountInsert
{
//define testmethod 
 public static testmethod void testinsert()
 {
//Create new account instance and pass your name as string input 
  Account a = new Account(name = 'SalesforceKid');
//Append Mr. with the account name
  a.name = 'Mr.' + a.name;
  insert a;
  }
} 
============================================

We just replicated what our trigger is performing in test class as well correct ?? that's what we have to check.

Scenario 3 :
Whenever a new record is created in account object. Before this new record is inserted into Account, delete all the contacts records with this account name.

Trigger :
============================================
trigger contactDeletion on Account(before insert)
{
//define list to store all the account names
 List<String> mynames = new List<String>();
//bulkifying for every new Account record 
  for(Account a : Trigger.New)
 {
//Add all account names in the list 
  mynames.add(a.name);
 }
//Query to get all the list of contacts where Name is like Name inside mynames
List<Contact> mycontacts = [SELECT Id, Name FROM Contact WHERE
                                                Name IN : mynames];
//delete all the mycontacts list from salesforce
delete myContacts;
}
============================================

Now let's write test class of the same salesforce apex trigger written above.

Test Class :
============================================
@isTest //Define Annotation of test class
public class AccountInsert
{
 public static testmethod void testdeletion()
 {
//Store any string name
  String myname = 'SalesforceKid';
 //Pass that string name as a Input to Account 
  Account a = new Account(name = myname);
//Pass lastname to contact as a string 
  Contact con = new Contact(lastname = 'Salesforcekid'); 
  insert con;
//Find out the contact with same name as Account string myname
   Contact c = [SELECT Id, Name FROM Contact WHERE Name =:                                      myname LIMIT 1];
   if(c != null)
  {
//Check whether the value of contact and account is similar
   System.assertEquals(c.Name, a.Name);
//Delete the contact if its not null
   delete c;
  }
//Then Lastly Insert The record 
insert a;
 }
}
============================================

I hope you understood the above test class. Once you write the apex test class inside Developer Console then click on the Run Test button. And make sure your test class will have more than 75% (85% for the safety side).

NOTE : Please note that I haven't used best practices in the above scenarios as this blog is specific to write  test classes for triggers 

In the next part, we will cover more trigger test classes along with the more trigger scenarios. So see yaa in the next episode

WOHOOO !! YOU HAVE JUST COMPLETED SALESFORCE TEST CLASS FOR TRIGGER EPISODE
If you like this salesforcekid learning platform please let me know in the Comment section...Also, Share with your salesforce folks wish you 
Happy learning ☁️⚡️ (Learn. Help. Share.)

<< PREVIOUS


Test Class For Trigger | Part 1 | Salesforce Test Class For Trigger | Part 1 | Salesforce Reviewed by on Rating: 5

No comments:

HELP !! SHARE !! SUGGEST !!

Powered by Blogger.