Today's Offer - Salesforce Certification Training - Enroll at Flat 10% Off.

- 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 to your Apex code. Test class code 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 sandbox. salesforce quiz 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 usedto 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 method for testing that same production code method should be avoided.
  8. Any asynchronous method testing should include Test.startTest and Test.stopTest.
  1. Use Test.isRunningTest() in your code to identify that context of class is Test or not. You can use this condition with OR (||) to allow test classes to enter inside code bock.
  2. @TestVisible annotation can be used to access private members and methods inside Test Class.

Creating Test Class

Read: What is Salesforce CRM and What does Salesforce do?

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 fire trigger by updating the records as we have done to start and stop block.

@isTest annotation:

Read: Salesforce Object Search Language (SOSL)

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():

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

Read: How to Improve Coding Skills & Become Better Salesforce Developer?

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 Handle Governor Limits 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();
    }  
}
 

Salesforce Tutorial Overview


    Janbask Training

    JanBask Training is a leading Global Online Training Provider through Live Sessions. The Live classes provide a blended approach of hands on experience along with theoretical knowledge which is driven by certified professionals.


Trending Courses

AWS

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

Upcoming Class

8 days 24 Dec 2019

DevOps

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

Upcoming Class

-1 day 15 Dec 2019

Data Science

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

Upcoming Class

-1 day 15 Dec 2019

Hadoop

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

Upcoming Class

0 day 16 Dec 2019

Salesforce

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

Upcoming Class

0 day 16 Dec 2019

QA

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

Upcoming Class

4 days 20 Dec 2019

Business Analyst

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

Upcoming Class

0 day 16 Dec 2019

SQL Server

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

Upcoming Class

4 days 20 Dec 2019

Comments

Search Posts

Reset

Receive Latest Materials and Offers on Salesforce Course

Interviews