Grab Deal : Flat 30% off on live classes + 2 free self-paced courses! - SCHEDULE CALL

- Salesforce Blogs -

What is Test Classes in Apex Salesforce?

Test Classes in Apex Salesforce

The Apex testing framework enables you to write and execute tests for your Apex classes and triggers on the Force.com platform. Apex unit tests ensure high quality for your Apex code and let you meet requirements for deploying Apex.

The testing framework tests your Apex code. Test class code is written in a sandbox environment and deployed to a production org. Apex unit tests are also requirements for deploying and distributing Apex. The following are the benefits of Apex unit tests. Apex test class makes sure the apex code works as expected

We write Test Classes in Apex Salesforce for Unit Testing. We get to find the bugs in our code and fix it to give better output. Testing gives the Code Coverage, first of all, we should know What Code Coverage is? Code coverage which shows to which percentage the code works. The minimum code coverage is 75% in order to be deployed to Production from the sandbox.

Please follow below salesforce Best Practice for Test Classes:-

  1. All test methods should reside in a separate class from the class in which the method being tested resides.
  2. @isTest annotation used to define a test class.
  3. The system.assertEquals used to know what is being tested and what the expected output
  4. The isTest(SeeAllData=true) annotation is used to open up data access when applied at the class or method level.
  5. All test data creation should be done from a Utility class.
  6. To run code for a specific user use annotation@ Test.runAs.
  7. Creating multiple test methods for testing that same production code method should be avoided.
  8. Any asynchronous method testing should include Test.startTest and Test.stopTest.
  9. Use Test.isRunningTest() in your code to identify whether the context of the class is Test or not. You can use this condition with OR (||) to allow test classes to enter inside code block.
  10. @TestVisible annotation can be used to access private members and methods inside Test Class.

Salesforce Training For Administrators & Developers

  • No cost for a Demo Class
  • Industry Expert as your Trainer
  • Available as per your schedule
  • Customer Support Available

Create, Run and Test a Test Class

Creating Test Class

Read: Top 1o4 Salesforce Apex Interview Questions and Answers

testMethod keyword:

Test.startTest() and Test.stopTest(): These are the standard test methods which are available for test classes. These methods contain the event or action for which we would be simulating our test.

Like in this example, we would be testing our trigger and helper class to simulate the firing trigger by updating the records as we have done to start and stop block.

@isTest annotation:

By using this annotation, you declared that this is a test class and it will not be counted against the organization's total code limit.

System.assert():

Read: Complete Advanced Administrator Salesforce Certification Guide [2023]

This method checks the expected output with the actual value. Trigger Example


trigger parent2child on Account (after update) {
list<id>ids = new list<id>();
list<contact>conlist = new list<contact>();
for(account a:trigger.new){
ids.add(a.id);
list<contact>con =[select id,phone,account.phone from contact where accountidin:ids];
for(contact c:con){
c.Phone=c.account.phone;
conlist.add(c);
        }

updateconlist;
     }       
 }
 

Test class @isTest


private class testForconPhone {
statictestMethod void testcheck()
    {
account a = new account();
a.Name='testing';
a.Phone='2222';
insert a;
accountaaa=[select name ,phone from account where id=:a.id];
contact c = new contact();
c.lastname=a.Name;
c.AccountId=a.id;
c.Phone='2222';
contact cc = new contact();
cc.lastname=a.Name;
cc.AccountId=a.id;
cc.Phone='111';
list<contact> c1 = new list<contact>();
        c1.add(c);
c1.add(cc);
insert c1;
try{
updateaaa;
        }
catch (exception e){

        }
system.assertEquals('2222','2222');       
    }
}

Run test Class What is Test Classes in Apex Salesforce? Click on run test What is Test Classes in Apex Salesforce? Here we find the code coverage percentage Batch class example


Global class batchexam2 implements Database.Batchable<sobject> {
globalDatabase.QueryLocator start(Database.BatchableContextbc){
string query='select id,lastName,Department from contact';
returnDatabase.getQueryLocator(query);
    }
global void execute (Database.BatchableContextbc ,list<contact>cons){
         //list<contact>
for(contact c:cons){
if(c.Department==null){
c.Department='Education';
            }
        }
update cons;
    }
    Global void finish(Database.BatchableContextbc){
batchexam ab= new batchexam();
database.executeBatch(ab);

        }
}
 

Test Class @isTest private class TestForbatchexam2 { @isTest


 private static void testbatchapex(){
list<contact>con = new list<contact>();
contact c = new contact();
c.LastName='Daniel';
c.FirstName='Jack';
c.Department=null;
con.add(c);
insert con;
test.startTest();
batchexam2 b = new batchexam2();
idjobid=Database.executeBatch(b,2);
test.stopTest();
list<contact> c1=[select lastname,Department from contact where id=:c.Id];
for(contact c2:c1){
if(c2.Department==null){
contact c3 = new contact();
            c3.LastName='philips';
            c3.Department='Education';
c1.add(c3);


        }
        }
update c1;
    }
}

Copy and paste the code and run test class Class example


public class insertExample {
public Account acc     {set;get;}
public string name     {set;get;}
public string industry {set;get;}
public string phone    {set;get;}
publicDMlex(){
acc=new Account();
    }
publicPageReference create(){
account a = new account ();
            a.name=name;
a.industry=industry;
a.Phone=phone;
insert a;
PageReference p = new PageReference('/'+a.Id);
return p;
    }
}

Test class @isTest

Read: The Ideal Salesforce Admin Tutorial For Beginners With Career Path & Certifications

@isTest
Private class DMLExampletest {
@isTest
    static void testme(){
       Account acc=new Account();
            acc.name='TCS';
            acc.Industry='Banking';        
            Insert acc;
        DMLExample De=new DMLExample();
        Account abc = new Account(Name='TCS');
            De.acc = abc;
            De.create();
        Account abc1 = new Account(Name='TCS2');
            De.acc = abc1;
            De.create();
    }  
}
 

Learn Salesforce in the Easiest Way

  • Learn from the videos
  • Learn anytime anywhere
  • Pocket-friendly mode of learning
  • Complimentary eBook available

Summary

Testing is an important part of Apex in Salesforce. Test classes are the code snippets that are developed to perform unit testing in Apex. You can utilize the above-mentioned practices to create a test class in Salesforce using Apex. If you have any other ideas, then don’t forget to mention that in the comments section below. Happy testing!



Salesforce Tutorial Overview

fbicons FaceBook twitterTwitter google+Google+ lingedinLinkedIn pinterest Pinterest emailEmail

     Logo

    JanBask Training

    A dynamic, highly professional, and a global online training course provider committed to propelling the next generation of technology learners with a whole new way of training experience.


  • fb-15
  • twitter-15
  • linkedin-15

Comments

Trending Courses

Cyber Security Course

Cyber Security

  • Introduction to cybersecurity
  • Cryptography and Secure Communication 
  • Cloud Computing Architectural Framework
  • Security Architectures and Models
Cyber Security Course

Upcoming Class

1 day 27 Apr 2024

QA Course

QA

  • Introduction and Software Testing
  • Software Test Life Cycle
  • Automation Testing and API Testing
  • Selenium framework development using Testing
QA Course

Upcoming Class

-0 day 26 Apr 2024

Salesforce Course

Salesforce

  • Salesforce Configuration Introduction
  • Security & Automation Process
  • Sales & Service Cloud
  • Apex Programming, SOQL & SOSL
Salesforce Course

Upcoming Class

-0 day 26 Apr 2024

Business Analyst Course

Business Analyst

  • BA & Stakeholders Overview
  • BPMN, Requirement Elicitation
  • BA Tools & Design Documents
  • Enterprise Analysis, Agile & Scrum
Business Analyst Course

Upcoming Class

1 day 27 Apr 2024

MS SQL Server Course

MS SQL Server

  • Introduction & Database Query
  • Programming, Indexes & System Functions
  • SSIS Package Development Procedures
  • SSRS Report Design
MS SQL Server Course

Upcoming Class

-0 day 26 Apr 2024

Data Science Course

Data Science

  • Data Science Introduction
  • Hadoop and Spark Overview
  • Python & Intro to R Programming
  • Machine Learning
Data Science Course

Upcoming Class

-0 day 26 Apr 2024

DevOps Course

DevOps

  • Intro to DevOps
  • GIT and Maven
  • Jenkins & Ansible
  • Docker and Cloud Computing
DevOps Course

Upcoming Class

8 days 04 May 2024

Hadoop Course

Hadoop

  • Architecture, HDFS & MapReduce
  • Unix Shell & Apache Pig Installation
  • HIVE Installation & User-Defined Functions
  • SQOOP & Hbase Installation
Hadoop Course

Upcoming Class

-0 day 26 Apr 2024

Python Course

Python

  • Features of Python
  • Python Editors and IDEs
  • Data types and Variables
  • Python File Operation
Python Course

Upcoming Class

8 days 04 May 2024

Artificial Intelligence Course

Artificial Intelligence

  • Components of AI
  • Categories of Machine Learning
  • Recurrent Neural Networks
  • Recurrent Neural Networks
Artificial Intelligence Course

Upcoming Class

1 day 27 Apr 2024

Machine Learning Course

Machine Learning

  • Introduction to Machine Learning & Python
  • Machine Learning: Supervised Learning
  • Machine Learning: Unsupervised Learning
Machine Learning Course

Upcoming Class

35 days 31 May 2024

 Tableau Course

Tableau

  • Introduction to Tableau Desktop
  • Data Transformation Methods
  • Configuring tableau server
  • Integration with R & Hadoop
 Tableau Course

Upcoming Class

-0 day 26 Apr 2024

Search Posts

Reset

Receive Latest Materials and Offers on Salesforce Course

Interviews