Test-Driven Development in Salesforce


 Concept - To Get some functionality working now and  improve or refactor it afterwards


Hi Developers !!. This post is regarding  Test Driven Development  approach in Salesforce. Before going into any details or explanation about  "Test Driven Development in Salesforce" we need to know about (Test-Driven Development).


 What is Test Driven Development (TDD) ?

 Test Driven Development is an evolutionary approach to development which combines test - first development where you write a test code before  you write just enough production code to fulfill that test and  refactor (making code clearer, cleaner and elegant) . We can also say that TDD is a method of software development in which UNIT Testing is repeatedly done on source code. TDD is a method which will help us to get a better code in less time with no defects.

 Benefits:

There are many benefits of using Test Driven Development approach for software development. Some of the benefits are :

1. Give confidence to developers
2. Manual Testing stage is shortened.
3. Time and Money spent in debugging at later stage is minimized.
4. Reduce Regression risk
5. In salesforce - Code coverage will be high.
6. Best way to fix the bugs.
7. Better to test New / Modified Functionality. ( existing functionality breaking chances will be very less).



Test Driven Development Approach:

In Test Driven Development Approach , we first write Test class rather than Code, So initially if we dont have a Class or handler class. .

Important Points regarding TDD:

1. Initially we will write the test code (at the point when there is no class), at that time the code will fail.. Yes it will !!
2. Then we will create class, controller class or  handler class according to our requirement and then we have to make sure all the test methods will pass.


The idea behind above two point is :


We will write the Test methods  first (which will fail ) and then we will write  the code which will get them to pass.

























Need for Unit tests:

The main benefits for Unit Testing are :

1. Better Quality, reduced risk of regressions
2. Reduce reworks on manual QA fail
3. Anticipate bugs in much cheaper than fixing them
4. Salesforce constraint: 75 % code coverage in order to deploy to live.

Best Practices in Salesforce:

There are some key points which we should always follow if possible as a Best Practices while writing Test class in Salesforce.

1. Do not rely on Org Data
2. Never use @isTest(SeeAllData= True) whenever possible except for PriceBooks.
4. If we need org data , limit to methods.
5. Uses TestData classes @isTest

Example :

The below class contains Test methods with different data access levels.
 @isTest  
 private class DifferentAccess {  
 // Method that has access to all data.  
    @isTest(SeeAlldata=true)  
     static void testwith() {  
  // can Query all data in the organization.  
 }  
 // method Test method that has access to only the data it creates  
  @isTest static void testwithOwnDataAccess(){  
   }  
 }  

Use Assertions:

1.Assertions are used for real Testing and validations.
2. Use Atleast 1 assert per test method.
3. Use message parameter to provide Context.

Syntax: (System.assert(Object,Object,message));

There are three types of System assert methods:

1. System.assert(Condition)
2. System.assertEquals(x,y)
3. System.assertNotEquals(x,y)

Positive and Negative Scenarios:

1. Validate success, failures and all relevant scenarios
2. Positive: execution with valid data/Parameters
3. Negative: execution with invalid data/Parameters
4. Use system.runAs( ) to test : Dynamic Apex, Methods using with sharing or without sharing and shared records.

Bulkify your Code:

Prepare and upload CSV of test data as Static Resources. Use it in Test classes. Syntax:

List<sObject> ls = Test.loadData(Account.sObjectType,'myResource') ;


Why Code Coverage is important :

Code coverage is a simple metric, expressed as a percentage, which describes the degree to which  the code of a program has been tested. In the context of Apex code, this percentage is calculated by dividing the number of lines of Apex code executed when your test methods run by the total number of Apex code lines.


Test-Driven Development Practical Example:

Scenario or User Story:  


Let us assume we have a business requirement where Sales user will not able to create a lead if the phone number of that lead already exists as Contact Phone Number. (Lead is having a lookup relationship to Contact Object)


According to Test Driven Development Approach we will first understand the requirement and write the Test methods and then write production code to pass our Test methods.

In this scenario I am writing a Trigger on Lead object where we will query Phone number from Contact Object and if a new lead's phone number will match with query result we will fire a validation rule. We will also follow the above best practices in this example.


Go to classes and create a Test class as below:

Analyse the requirement to write a Test class.

Possibilities:

1. Lead phone Number is Unique or there is no contact with same phone number.
2. Lead  phone number  is already existing.

According to Requirement we will decide how many test methods will be there in our test class. In the current Scenario we are checking above two possibilities , so we will create two methods in our class.

 @isTest  
 public class TestDuplicateLead {  
   static testMethod void testNonDuplicate() {  
    // Create a lead record where Phone number of a lead does not exists as record  
     Lead le   = new Lead();  
     le.FirstName = 'Bavesh';  
     le.LastName = 'Sanan';  
     le.Company  = 'Extentor Tquila';  
     le.Phone   = '9988062669';  
     insert le ;  
    // Query Phone Number from Contact.  
    List<Lead> leadPhoneUnique = [Select Id FROM Lead where Phone = '9988062669'];  
    System.assertEquals(1, leadPhoneUnique.size());  
   }  
   static testMethod void testDuplicate() {  
     // create a test record for Contact  
     Contact con  = new Contact();  
     con.FirstName = 'Bavesh';  
     con.LastName = 'Sanan';  
     con.Phone   = '7406317630';  
     insert con;  
     // Now we will create a Lead record with same Phone number as Above contact's Phone number  
     Lead lea   = new Lead();  
     lea.FirstName = 'Bavesh';  
     lea.LastName = 'Sanan';  
     lea.Company  = 'Extentor Tquila';  
     lea.Phone   = '7406317630';  
     try{  
        insert lea;  
    } Catch(Exception e){  
        System.debug('Catch It !!');  
    }  
    // Query Phone Number from Contact.  
    List<Lead> leadPhone = [Select Id FROM Lead where Phone = '7406317630'];  
    System.assertEquals(0, leadPhone.size());  
     }  
 }  
Trigger:

Now as we completely understood the requirement and also wrote the test class now we will write production code to pass above test class or methods.



 trigger LeadDuplicate on Lead (before insert, before update) {  
  for (Lead newLead : Trigger.new) {  
   if (newLead.Phone!= null) {  
    List<Contact> cont = [SELECT Id FROM Contact  
                 WHERE Phone= :newLead.Phone];  
    if (cont.size() > 0) {  
     newLead.Contact__c= cont[0].Id;  
    } else {  
     newLead.Contact__c= null;  
     }                
    }  
   }  
 }  


As we know Contact is a look up field on Lead object, so once the size of the Contact list will be greater than 0, the validation will fire.



Hope this Blog will help you to understand TDD approach !!!


                                                Enjoy Coding !!!!

                                         



Comments

  1. Nice post! In coming years, cloud computing is going to rule the world. The cloud based CRM tool provider like Salesforce have massive demand in the market. Thus talking salesforce training in Chennai from reputed Salesforce training institutes in Chennai will ensure bright career prospects for aspiring professionals.

    ReplyDelete
  2. I am really thankful for posting such useful information. It really made me understand lot of important concepts in the topic. Keep up the good work!
    Oracle Training in Chennai | Oracle Course in Chennai

    ReplyDelete
  3. Appreciation for really being thoughtful and also for deciding on certain marvelous guides most people really want to be aware of....
    Aws training chennai | AWS course in chennai
    Rpa training in chennai | RPA training course chennai
    sas training in chennai | sas training class in chennai

    ReplyDelete
  4. Very nice blogs!!! i have to learning for lot of information for this sites…Sharing for wonderful information.Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing
    Java Training in Chennai

    Java Training in Velachery

    Java Training inTambaram

    Java Training in Porur

    Java Training in Omr

    Java Training in Annanagar

    ReplyDelete
  5. Nice post! In coming years, cloud computing is going to rule the world. The cloud based CRM tool provider like Salesforce have massive demand in the market
    Digital Marketing Training in Velachery

    Digital Marketing Training in Tambaram

    Digital Marketing Training in Porur

    Digital Marketing Training in Omr

    Digital MarketingTraining in Annanagar


    ReplyDelete

  6. Come up with a great learning experience of Azure training in Chennai, from Infycle Technologies, the best software training institute in Chennai. Get up with other technical courses like Data Science, Selenium Automation Testing, Mobile App Development, Cyber Security, Big Data, Full Stack Development with a great learning experience and outstanding placements in top IT firms. For best offers with learning, reach us on +91-7504633633, +91-7502633633

    ReplyDelete

Post a Comment

Popular posts from this blog

Setting a default 'From' address when sending an email from Cases

Email Messaging from Salesforce