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;
}
}
}
}
Hope this Blog will help you to understand TDD approach !!!
Enjoy Coding !!!!
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.
ReplyDeleteYour blog is nice. I believe this will surely help the readers who are really in need of this vital piece of information. Thanks for sharing and kindly keep updating.
ReplyDeleteBest Spoken English Training Institute in Adyar
Spoken English Classes in Gandhi Nagar
Spoken English Classes in ECR
Spoken English Center in Porur
Spoken English in Ramapuram
Spoken English Classes in Moulivakkam
Spoken English Course near me
It has been simply incredibly generous with you to provide openly what exactly many individuals would’ve marketed for an eBook to end up making some cash for their end, primarily given that you could have tried it in the event you wanted.
ReplyDeletelinux Training in Chennai | Best linux Training Institute in Chennai
Unix Training in Chennai | Best Unix Training Institute in Chennai
Sql Training in Chennai | Best Sql Training Institute in Chennai
Oracle Training in Chennai | Best Oracle Training Institute in Chennai
Digital Marketing Training in Chennai | Best Digital Marketing Training Institute in Chennai
Best Hand Blender india
ReplyDeleteonline earning whatsapp groups
ReplyDeleteI 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!
ReplyDeleteOracle Training in Chennai | Oracle Course in Chennai
Appreciation for really being thoughtful and also for deciding on certain marvelous guides most people really want to be aware of....
ReplyDeleteAws training chennai | AWS course in chennai
Rpa training in chennai | RPA training course chennai
sas training in chennai | sas training class in chennai
Thanks for this wonderful Blogs...Good to see the Powerful contents,Keep going with the same
ReplyDeleteJava training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery
This concept is a good way to enhance the knowledge.thanks for sharing. please keep it up
ReplyDeleteSalesforce Training | Online Course | Certification in chennai | Salesforce Training | Online Course | Certification in bangalore | Salesforce Training | Online Course | Certification in hyderabad | Salesforce Training | Online Course | Certification in pune
Thank you a lot for providing individuals with a very spectacular possibility to read critical reviews from this site.
ReplyDeleteSalesforce Training | Online Course | Certification in chennai | Salesforce Training | Online Course | Certification in bangalore | Salesforce Training | Online Course | Certification in hyderabad | Salesforce Training | Online Course | Certification in pune
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
ReplyDeleteJava Training in Chennai
Java Training in Velachery
Java Training inTambaram
Java Training in Porur
Java Training in Omr
Java Training in Annanagar
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
ReplyDeleteDigital Marketing Training in Velachery
Digital Marketing Training in Tambaram
Digital Marketing Training in Porur
Digital Marketing Training in Omr
Digital MarketingTraining in Annanagar
Awesome Post. It was a pleasure reading your article. Thanks for sharing.
ReplyDeleteSoftware Testing Training in Chennai
Software Testing Training in Velachery
Software Testing Training in Tambaram
Software Testing Training in Porur
Software Testing Training in Omr
Software Testing Training in Annanagar
ReplyDeleteCome 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