Our Support: During the COVID-19 outbreak, we request learners to CALL US for Special Discounts!

- 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 [email protected] 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: Future Growth of a Salesforce Developer in 2020

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: How to Create an App in SFDC?

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: How To Start Your Career In Salesforce?

@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


    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.


Comments

Trending Courses

AWS

  • AWS & Fundamentals of Linux
  • Amazon Simple Storage Service
  • Elastic Compute Cloud
  • Databases Overview & Amazon Route 53

Upcoming Class

5 days 13 Aug 2020

DevOps

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

Upcoming Class

2 days 10 Aug 2020

Data Science

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

Upcoming Class

9 days 17 Aug 2020

Hadoop

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

Upcoming Class

-1 day 07 Aug 2020

Salesforce

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

Upcoming Class

2 days 10 Aug 2020

QA

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

Upcoming Class

-1 day 07 Aug 2020

Business Analyst

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

Upcoming Class

6 days 14 Aug 2020

MS SQL Server

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

Upcoming Class

6 days 14 Aug 2020

Python

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

Upcoming Class

-1 day 07 Aug 2020

Artificial Intelligence

  • Components of AI
  • Categories of Machine Learning
  • Recurrent Neural Networks
  • Recurrent Neural Networks

Upcoming Class

-1 day 07 Aug 2020

Machine Learning

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

Upcoming Class

8 days 16 Aug 2020

Tableau

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

Upcoming Class

-1 day 07 Aug 2020

Search Posts

Reset

Receive Latest Materials and Offers on Salesforce Course

Interviews