Our Blog

Test Classes In Apex Salesforce

Test Classes In Apex Salesforce

Before Knowing how to write Test Classes In Apex Salesforce we should why we write Test Classes.

Need Of Writing Test Classes

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? It is the line of code which are covered through testing.The code must have 75% code coverage in order to be deployed to Production. It is discussed further below.

Data Access

@isTest annotation:
The test class are written under @isTest annotation. By using this annotation for test class we maintain code limit as it is not counted in it.

Create Raw-Data At First:
The Test Class In Apex Salesforce does not have access to any of the data which is stored in the related Salesforce org by default.We need to create raw-data for test class in our test class itself. By adding SeeAllData=true to @isTest annotation i.e. @isTest(SeeAllData=true) grants the access to the all the data of the related Salesforce org.

Code

Test Class for trigger:
Here is the Trigger for which we will be writing test class:

trigger bookTrigger on book__c (before insert) {
        
        /**
         * Webkul Software.
         *
         * @category  Webkul
         * @author    Webkul
         * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
         * @license   https://store.webkul.com/license.html
         */
        
        list<book__c> li = trigger.new;
        
        for(book__c str : li){
            str.Price__c = str.Price__c * 0.8;
        } 
        
}

Now the test class will be as follows:

@isTest
private class bookTriggerTest {

    /**
     * Webkul Software.
     *
     * @category  Webkul
     * @author    Webkul
     * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
     * @license   https://store.webkul.com/license.html
     */

    static testMethod void validateHelloWorld() {
       Book__c b = new Book__c(Name='Behind the Cloud', Price__c=100);
       System.debug('Price before inserting new book: ' + b.Price__c);

      // Insert book
       insert b;

       // Retrieve the new book
       b = [SELECT Price__c FROM Book__c WHERE Id =:b.Id];
       System.debug('Price after trigger fired: ' + b.Price__c);

       // Test that the trigger correctly updated the price
       System.assertEquals(80, b.Price__c);
    }
}

Test Class For Extension:
Here is the Controller Extension for which we will be writing test class:

public with sharing class contactext {
    
   /**
    * Webkul Software.
    *
    * @category  Webkul
    * @author    Webkul
    * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
    * @license   https://store.webkul.com/license.html
    */

    public contact con;
    
    public contactext(ApexPages.StandardController std){
        
            con = (contact)std.getrecord();
            
    }
    
    public pagereference savedata(){
    
        try{
        
            insert con;
            apexpages.addmessage(new apexpages.Message(apexpages.severity.confirm,'Contact Saved'));
        
        }catch(exception e){
        
            apexpages.addMessages(e);
        
        }
        
        pagereference pg = page.Task02_Contactext;
        pg.setredirect(true);
    
        return pg;
    
    }    
    
}

Now the test class will be as follows:

@isTest
public class contactextTest
{

   /**
    * Webkul Software.
    *
    * @category  Webkul
    * @author    Webkul
    * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
    * @license   https://store.webkul.com/license.html
    */

   @isTest static void testMethodForException()//Checking Records for exception
    {
	Account testAccount = new Account();//Insert Account
        testAccount.Name='Test Account' ;
        insert testAccount;
        Contact cont = new Contact();
        cont.FirstName ='Test';
        cont.LastName ='Test';
        cont.accountid =testAccount.id;
        insert cont;
        ApexPages.StandardController sc = new ApexPages.StandardController(cont);
        contactext contactextObj = new contactext(sc);//Instantiate the Class
        try
        {
            contactextObj.savedata();//Call the Method
        }
        catch(Exception e)
        {}
        list<account> acc = [select id from account];//Retrive the record
        integer i = acc.size();
        system.assertEquals(1,i);//Test that the record is inserted        
        
    }
	@isTest static void testMethod1()//Testing the insertion method
    {
        Account testAccount = new Account();//Insert Account
        testAccount.Name='Test Account' ;
        insert testAccount;
        Contact cont = new Contact();
        cont.FirstName ='Test';
        cont.LastName ='Test';
       cont.accountid =testAccount.id;
	  
            try
            {
                ApexPages.StandardController sc = new ApexPages.StandardController(cont);
                contactext contactextObj = new contactext(sc);//Instantiate the Class
                contactextObj.savedata();
	         }
            catch(Exception ee)
            {}
            list<account> acc = [select id from account];//Retrive the record
	        integer i = acc.size();
	        system.assertEquals(1,i);//Test that the record is inserted
        
    }     
}

Test Class For Controller:
Here is the class for which we will be writing test class:

public with sharing class retrieveAcc {
    
    /**
     * Webkul Software.
     *
     * @category  Webkul
     * @author    Webkul
     * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
     * @license   https://store.webkul.com/license.html
     */

    public list<account> getacc(){
    	
    	list<account> li = [select Name,AccountNumber,AccountSource,ParentId from account];
    	
    	if(li!=null && !li.isEmpty()){
    	
    		return li;
    	
    	}else{
    	
    		return new list<account>();
    	
    	}    
    	
    }
    
}

Now the test class will be as follows:

@isTest
private class retriveAccTest {

        /**
         * Webkul Software.
         *
         * @category  Webkul
         * @author    Webkul
         * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
         * @license   https://store.webkul.com/license.html
         */

	@isTest static void testmeth1(){
		//Insert Record for testing the If situation
		account acc1 = new account(name = 'acc1', AccountSource = 'Web');
		account acc2 = new account(name = 'acc2', AccountSource = 'Web');
		list<account> accList = new list<account>();
		accList.add(acc1);
		accList.add(acc2);
		insert accList;
		
		//Test that Records are Inserted
		list<account> obj1 = new retrieveAcc().getacc();
		system.assertequals(obj1.size(),2);
		
		//Delete Records For testing the Else situation
		delete accList;
		
		//Test that Records are Deleted
		list<account> obj2 = new retrieveAcc().getacc();
		system.assertEquals(obj2.size(),0); 
	}     
}

 

How to Run A Test Class In Developer Console

Step-1:
Open the Developer Console Window.Step1

Step-2:Step2

Step-3:Step3

Step-4:Last

Code Coverage:CodeCoverage

CodeCoverage2

 

Support

That’s all for Implementing Test Classes In Apex Salesforce, still have any issue feel free to add a ticket and let us know your views to make the code better https://webkul.uvdesk.com/en/customer/create-ticket/

 

Read More:How to Delete it using Apex in Salesforce?

 

Leave a Comment

Comments (0)

Please verify that you are not a robot.

Welcome back

Welcome back! Please enter your details

One or more fields have an error. Please check and try again.

Forgot Password?

Tell us about Your Company

How can we help you with your business?









    css.php