Category: Salesforce Apex

Testing Apex | Apex Unit Test, Run Unit Test Methods

Testing Apex – Apex Unit Test

Testing is the key to successful long term development and is critical component of development process. Salesforce Apex, provides a testing framework which allows developers to write Apex unit test, run tests, check test results and code coverage. In this Salesforce tutorial, we will understand testing in Apex, what to Test in Apex and What are Apex Unit Tests.

Testing Apex

Testing is the key to success for an application. If we want to validate the working of an application, then we can test an application in two ways.

  1. Using Salesforce user interface.
  2. Testing bulk Functionality.

When an application is tested using Salesforce user interface, this will not catch all cases that are important to application. Through bulk functionality we can pass up to 200 records only through our code.

Before deploying code or package to the AppExchange, the following conditions must be true.

  • At least 75% of your Apex code must be covered by unit tests.
  • All the test cases will be successful.
  • Every trigger must have some test coverage.
  • All classes and triggers must compile successfully.

Factors that need to be tested in Apex Programming.

  • Single action – This is to test a single record, produces the correct expected result.
  • Bulk actions – Any Apex code, whether a trigger, a class or an extension, may be invoked for 1 to 200 records. We must test not only single record case but also bulk cases.
  • Positive behaviour – Test to verify that the expected behaviour occurs through every expected permutation or not.
  • Negative behaviour – Some limits are applicable to an application like future date must not be added.
  • Restricted User – Test whether a user with restricted access to the sObjects used in your code sees the expected behavior.

What are Apex Unit test?

Apex supports creating and executing Apex unit test for robust and error free code. So what is Apex unit tests? Apex unit test is a class method which verify the working behaviour of the Apex code.Apex unit test takes no arguments, no data to database and sends no email.

When we want to create a test method in Apex, we must use testmethod Keyword or @isTest annotation. All test methods are static and can’t be defined in triggers.

Example :

@isTest annotation

If we define any method as @isTest then the method is termed as testmethod.


What is an Interface in Apex | Definition

What is an Interface in Apex

Interface in Apex is a collection of unimplemented methods and it contains the method signature, but the body of each method is empty. To use Interface in Apex, another Apex class must implement it by providing the body for all the methods contained in Apex interfaces. Interface in Apex are given as global.


All the methods in the interface are public and abstract methods. Interface also contains, Final Static Data members. The Class which is implemented this interface should define all the methods in the interface.

  • Interfaces can provide a layer of abstraction for our code.
  • Defining an Interface in Apex is similar to defining a new class in Apex.


We should define method in the interface, if not it will display an error. For interface in Apex, we can not create an object.

  • Demo d = new Demo ( ); is not allowed because interface in Apex contains only unimplemented methods and static methods.
  • Demo d = e; is allowed because ‘e’ is the object of the class which is implementing the demo interface.
  • Demo d = t; is not allowed because test class in not implemented interface demo.

Interface Iterator.

This is the interface defined by Salesforce in Apex. Interface Iterator has 2 methods .

Boolean hasNext( )

Boolean hasNext( ) method return true if there is another item in the collection being traverse else returns ‘false’

AnyType next()

AnyType next() method returns the next item in the collection. Both methods given above should be declared as a global or public

How to create Custom Iterator in Apex.

Interface iterable

Iterable is interface in which we have a method Iteratorclass Iterator()



Visualforce page

Salesforce Apex DML Statements – Data Manipulation Language

Salesforce Apex DML Statements

Salesforce Apex DML (Data Manipulation Language) statements are used to Insert, Update, Merge, Delete and restore data in Salesforce. We can perform DML operations using the Apex DML statements or the methods of the Database class. We can perform 6 DML operations they are

  1. Insert.
  2. Update.
  3. Delete.
  4. UpSert.
  5. Merge and
  6. Restore.

Salesforce Apex DML statements

Insert DML Statement

The insert DML operation adds one or more sObjects, such as individual accounts or contacts, to your organization’s data. insert is analogous to the INSERT statement in SQL.



Update DML Statement

The update DML operation modifies one or more existing sObject records, such as individual accounts or contacts, invoice statements, in your organization’s data. Update is analogous to the UPDATE statement in SQL.



Upsert DML Statement

The upsert DML operation creates new records and updates sObject records within a single statement, using a specified field to determine the presence of existing objects, or the ID field if no field is specified.



Delete DML Statement

The delete DML operation deletes one or more existing sObject records, such as individual accounts or contacts, from your organization’s data. Delete is analogous to the delete() statement in the SOAP API.



Undelete DML Statement

The undelete DML operation restores one or more existing sObject records, such as individual accounts or contacts, from your organization’s Recycle Bin. undelete is analogous to the UNDELETE statement in SQL.    



Merge DML Statement

The merge statement merges up to three records of the same sObject type into one of the records, deleting the others, and re-parenting any related records.This DML operation does not have a matching Database system method.



Different ways to perform DML operations.

  1. By using DML Statements
  2. By using Database Class.

By using DML Statements.

By using Database Class.

As shown above, there is one difference between the two operations. In the database class method, we can specify whether to allow partial processing of the records if any errors are encountered by paring the boolean values as a parameters to Database.insert.

  • If we give the parameter as ‘True’. if any error occurs it doesn’t allow the operation to continue.
  • If we give the parameter as ‘false’, the remaining DML operations can still succeed. Where as insert in DML if any one of the record fails the total operation is discarded.

Email Messages in Salesforce | Inbound, Outbound Messages

Email Messages in Salesforce are powerful, robust and provide secure functionality to send an Email from Salesforce. In this Salesforce tutorial, we will learn about Email Programming, different types of email, What is Single Email Messages in Salesforce and Methods, What is Mass Email Message in Salesforce, Attaching files to outbound emails, Attaching documents to outbound email messages in Salesforce.

  1. Types of Email Services in Salesforce.
  2. Outbound Email Messaging.

Email Messages in Salesforce

Email Messages in Salesforce are powerful, robust and provide secure functionality to send an Email from Salesforce. It is very important to send and receive an Email from Salesforce to the external system then we use Email services. In Salesforce, we have two types of Email Services they are

Email Messages in Salesforce | Inbound, Outbound Messages

  1. Inbound Email Messaging
  2. Outbound Email Messaging.

Outbound Email Messaging

Outbound Email Messaging is used to send an Email to external system using Apex Code. They are 2 types of outbound Emails.

  1. Single Email Message.
  2. Mass Email Message.

Single Email Message

Single Email Message instantiates an email object used for sending a single email message.


As shown in above class, Messaging name space provides classes and methods for Salesforce outbound and Inbound email services. The methods in the above class sends single email message to external system. To send single email message, first we have to create an object for SingleEmailmessage.

SingleEmailMessage Methods

Single Email message consists of nearly 19 methods that can be used in Email messages in Salesforce.


This method will set Bcc Address to the whom the email should be sent. We can set up to 25 email addresses.


This method will set CcAddress to whom the mail should be sent. We can set utp 25 email address.


This method will set the address, we can set up to 100 addresses.


setSubject( ) method will set the subject of mail.


setPlainTextBody() will set the main body of the mail.


setHtmlBody( ) will set the main body of the mail.


Through MassEmailMessage we can send a mass email messages to a recipient list that consists of contacts, Leads, Person accounts or users you can view in Salesforce.


Messaging.MassEmailMessage class all the methods defined in the Email class and also Email base class methods.

Signature : public MassEmailMessage()

Mass Email Message Methods

  • setDescription(description) : This will give the description about the mail.
  • setTargetObjectIds(targetObjectIds) : We can add upto 250 IDs per email. If you specify a value for the target Object Id’s field optionally specify a WhatID’s as well.
  • setWhatIds(whatIds) : This values can be . any one of the following contact, case, opportunity and product.


What is Constructor in Apex Programming

What is Constructor in Apex Programming?

Constructor in Apex Programming is a code and is a special method that is invoked when an object is created from the class. Constructor has the following properties.

  1. Method name will be same as Class.
  2. Access specifier will be public.
  3. This method will invoked only one that is at the time of creating an object.
  4. This is used to instantiate the data members of the class.

Example :

Types of Constructor in Apex programming.

  1. Default Constructor.
  2. Non-parameterized Constructor.
  3. Parameterized Constructor.

Default Constructor

If an Apex Class doesn’t contain any constructor then Apex Compiler by default creates a dummy constructor on the name of class when we create an object for the class.

As shown in above example, the Apex class doesn’t contain any Constructor. So when we create object for example class the Apex compiler creates a default constructor.

Non-parameterized Constructor & parameterized Constructor.

It is a constructor that doesn’t have any parameters or constructor that has parameters.

Apex Class

Constructor in Apex programming with example

To create an Constructor in Apex programming, first we need to write an Apex class. To write an Apex class login to Salesforce and navigate to developer console and click on file.

  • Select new Apex class and name the class.

Apex Class

  • Now open anonymous block.

What is Constructor in Apex Programming

Click on Execute button.

  • If we want to write a constructor with argument (parameterised constructor), then we ca nuse that constructor to create an object using those argument.
  • If a class contain parameterised constructor, the default constructor won’t create automatically. We need to create no-argument constructor explicitly.
  • Constructor in Apex programming can be overloaded.
  • Constructor in Apex programming can call another constructor using (…) syntax. This is also called as Constructor Chaining.

Write an Apex Class to perform addition, subtraction and Multiplication

In this Salesforce tutorial, we are going to write an Apex Class to perform addition, subtraction and multiplication based on the button we clicked. And also we learn how to call Apex method in a Visualforce page.

How to write an Apex Class?

Apex class is a collection of data members and methods. Let us learn how to write an Apex Class. To write an Apex class navigate to Developer Console | File | New | Apex Class.

  • Enter the name for Apex Class.

Apex Class

Write an Apex Class to perform addition, subtraction and Multiplication

  • Integer and String are the Data members of the class.
  • System.

How to call the Apex methods in a Visualforce page.

Apex class

  • return null : When we give return null, it will come back to the same page.
  • pageReference is the return type of every method that we have called from Visualforce page.

Visualforce page

  • When we click on the “Click” button it will invoke pageReference Show() method.

Apex Class to perform addition, subtraction and Multiplication.

In our previous Salesforce tutorial, we have learned about Apex Setter method and Getter method. We can also define Setter and getter methods in a single line.

  • public Integer{set;get;}

Apex Class.

As shown above, we have named the Apex class as Subtraction.

Visualforce page

In the above Visualforce page, we have added some Visualforce components like <apex:form>, <apex:pageBlock>, <apex:pageBlockSection>, <apex:pageBlockSectionItem>,<apex:commandButton>. All these components are for Styling, adding buttons like Salesforce Salesforce buttons.

  • <apex:pageBlockSection> consists of one or more columns.


As shown above example, enter X value and Y value then click on Addition or Subtraction or Multiplication button. Suppose when we click on Multiplication, the result will be displayed in Result section.

Apex Getter and Setter methods with examples

Apex Getter and Setter methods

When we want to refer Apex class variables in the visualforce page we need to use Apex getter and setter methods. In this Salesforce tutorial, we will understand about Apex getter method and setter method in detail.

  • Setter method : This will take the value from the visualforce page and stores to the Apex variable name.
  • getter method : This method will return a value to a visualforce page whenever a name variable is called.

get method ( )

When visualforce page want to get the value of a variable defined in the Apex. It will invoke get method of that variable.

Example : <apex:outputlabel > {!name} </apex:outputlabel>.

In the above example, Visualforce page is trying to use name variable which is declared in Apex class. So it invokes automatically getname( ) method in the Apex class and this method will return the value of that variable.

Example for getter method using visualforce and Apex class.

Visualforce page

As shown above, when the page is loaded first it creates an object for prasanth class. When outputlabel calls {!name} in the Visualforce page, it invokes getname( ) method in the controller class.


Apex Getter and Setter methods

Setter method

Setter method  will take the value from the visualforce page and stores to the Apex variable name.To understand about setter method ( ), let us write an Apex class for passing the values and saving the values to Apex variables.

Write an Apex class to demonstrate Setter method.

Visualforce page

In the above example, we have written simple Apex code to pass the values and save the values to Apex variables.


Apex Getter and Setter methods

Apex Class Variables, Class Methods, Object

Apex Class Variables

In this Salesforce tutorial, we will learn about Apex Class Variables, class methods and objects.

The variables in the class should specify the following properties when they are defined.

  1. Optional : Modifiers such as public or final as well as static.
  2. Required : The data type of the variable, such as String or Boolean.
  3. Optional : The value of the variable.
  4. Optional : The name of the variable.

Class Methods

To define a method specify the following

  1. Optional : The data type of the value returned by the method, Such as String or Integer use void if the method does not return a value.
  2. Required : A list of input parameter for the method separated by commas, each preceded by  its data type, and enclosed in parentheses(). If there are not parameters, use a set of empty parentheses.
  3. A method can only have 32 input parameters.
  4. Required : The body of the method, enclosed in braces { }. All the code for the method, including any local variable declarations is contained base.

Syntax :

Example :


Object is a instance of a class. This has both State and behaviour. Memory for the data members are allocated only when you create a object.


Example :