How To Write Test Class In Salesforce

In order to enjoy the benefits of reduced tasking and automated processes of online business management, you should learn simple basics of how to write test class in Salesforce.

A test class simply refers to the input required to confirm if instructions and methods used in developing an application or program are working correctly in delivering the desired output. Tests can be written for many classes to gauge their accuracy and correct any overlaps or missing links in order to achieve a streamlined process with accurate results.

Basic Steps of How to Write Test Class in Salesforce

How To Write Test Class In Salesforce

Since Salesforce is concerned with activities shared across the cloud, they require at least 75% of the code to be tested before it can be lodged into the organization. This is basically to prevent overlap and breaking the cloud. There are different test classes that can be written and run to achieve the 75% minimum requirement tests on task codes.

The first test class is aimed at verifying credibility of data by setting tests that identify True and False. The test can be set to either although there are boundaries that guide this selection. The most preferred test is “@isTest”

Consider the following test class.

@isTest(seeAllData=true)
private class Test_CountContactOfAccount { 

//Method
static testMethod void CountContactOfAccountUnitTest() { } }

(seeAllData=true)


• The above script/code is used when querying an object by fetching records from a database in the test class. This allows for testing object records such as “OpportunityLineItem”.

• When the test record of the object is inserted and then queried in the test class, then it should be set to false (seeAllData=false).

The second test class is used in deploying a simple trigger. A trigger mainly refers to a code that runs either before or after a specific action is done on a record for example insert, delete, update or undelete. To test a trigger, one must first create an apex class which acts on the record in the requested way (for example inserting record) to initiate the trigger code execution.

To create an apex class in salesforce, go to Setup then Develop, then Apex Classes and select New. 
Now consider the following test code used when inserting a new user. The simple trigger should execute when a new user is inserted and if 75% of the codes are run, then salesforce will allow deployment of the trigger to production.

First set of codes

@isTest 
public class Forecasting {
static testMethod void addNewUser() {

User userToCreate = new User();

// Do you recognize these fields?
userToCreate.FirstName = ‘Bonface’;
userToCreate.LastName = ‘Kambona’;
userToCreate.Email = ‘bnfc+kmbna@gmail.com’;
userToCreate.Username = ‘amby-xxxx@gmail.com’;
userToCreate.Alias = ‘fatty’;
userToCreate.ProfileId = ’01er0010000iTqy’;

 

Second set of codes

// Don’t worry about these fields
userToCreate.TimeZoneSidKey = ‘Kenyan/Nairobi’;
userToCreate.LocaleSidKey = ‘en_KN’;
userToCreate.EmailEncodingKey = ‘UTF-6’;
userToCreate.LanguageLocaleKey = ‘en_KN’;

insert userToCreate; }}

The above code has 5 lines of execution therefore if four of them are run and tested, then the 75% requirement is a pass. In this case, all of them will be executed. The second set of codes is not essential and only help in further descriptions.

pNow let us break down what the test class code does and how they are created.

@isTest 
public class Forecasting {
static testMethod void addNewUser() {

This code is basically used to inform salesforce that you are writing a test (teSettingsst code). These lines are virtually the same regardless of what is being tested and are therefore very important.

User userToCreate = new User();

The above code line shows what is used when creating a new record in Apex and the object can be changed depending the record being created. 

// Do you recognize these fields?
The above line simply refers to how comments are written in Apex. Salesforce will skip any line of code that begins with the // sign.
// Do you recognize these fields?
userToCreate.FirstName = ‘Bonface’;
userToCreate.LastName = ‘Kambona’;
userToCreate.Email = ‘bnfc+kmbna@gmail.com’;
userToCreate.Username = ‘amby-xxxx@gmail.com’;
userToCreate.Alias = ‘fatty’;

userToCreate.ProfileId = ’01er0010000iTqy’;

The above set of codes is used for inserting/setting the fields needed for the new user being created. The last line has been deliberately separated since its function is to populate a lookup field with the ProfileId. All the above fields are very important and required when creating a new user. After the code has been written, you can run it to get a preview of the test result which is displayed in a dialog box. The result will indicate how many lines of codes were successfully run and whether they meet the minimum 75% requirement.

test class in salesforce


Explanation of Used Variables

In the above test class, the variables used include:

• @isTest – this simply informs Salesforce the code is for test purposes

• Forecasting – this refers to the name I have chosen for the test class. It is useful in organizing the code like a folder within a database.
• testMethod – this is a repeat message to remind salesforce that it is a test code.
• addNewUser – this is the name I have chosen for the test method. It can be compared to a document inside the folder (test class). A test class may have several methods.
• User – this is the API name given to Salesforce objects (sObject) and the one used here is the standard user object.
• userToCreate – this variable is named to store the new user record created.
• = ’01er0010000iTqy’ – this is the ID given to the new user profile created. IDs should be wrapped inside a single quote just like texts and it can be different provided they add up to 15 characters (letters and numbers).
• insert – this is used as a DML statement to enable creating the record in the org.

Conclusion

When writing a test class it is important to use the data from scratch. In other words this needs an assumption that the code will be deployed in an org with no records. This ensures the test class still works even if an object gets deleted. It is also important to run bulk tests including some that are not supposed to work in order to identify mistakes. When the above test is run and functions correctly, it can then be deployed in a production environment. Salesforce usually requires all codes to be tested to ensure they are running efficiently and producing the desired results before running them on the production organization. There are many types of test classes that can be written and run but they revolve around the above example of how to write test class in Salesforce.

Readers who want to learn more about adding test classes in Salesforce can discover even more here.

For further information about triggers read Salesforce trigger best practices.

Amanda McDonnald
Amanda is the Lead Author & Editor of Rainforce Blog. Amanda established the Rainforce blog to create a source for news and discussion about some of the issues, challenges, news, and ideas relating to Salesforce usage.
Amanda McDonnald on sabtwitterAmanda McDonnald on sabgoogle