Concept of Unit Testing & Test classes in Salesfoce

Unit Testing:

Unit tests are class methods that verify whether a particular piece of code is working properly. Unit test methods take no arguments, commit no data to the database, send no emails, and are flagged with the testMethod keyword in the method definition.

Classes defined with the isTest annotation don’t count against your organization limit of 2 MB for all Apex code. Individual methods defined with the isTest annotation do count against your organization limits.

You can run unit tests for:
– A specific class
– A subset of classes
– All unit tests in your organization

To run a test, use any of the following:
– The Salesforce user interface
– The Force.com IDE
– The API

Required Average test coverage across all Apex Classes and Triggers is 75%.

Considerations:

Test methods cannot be used to test Web service API.
You can’t send email from test method
Since test method doesn’t commit data creation, you need not delete upon completion.
In Feed tracking, they don’t result in creation of Feed Tracked changes records.

Sample Class:

public class SampleClass
{
public void insertAcct(String name, String extId)
{
Account acc = new Account(Name = name,External_ID__c = extId);
insert acc;
}
}

Test Class for Sample Class:

@isTest

private class MyTestClass
{
static testMethod void insertAcc()
{
SampleClass sc = new SampleClass();
sc.insertAcct(‘Test Account’,’100′);
}
}

How to avoid Salesforce Governor Limits in Test class in Salesforce?

Test.startTest() and Test.stopTest() are very useful when your test class hits Salesforce Governor Limits.

The code inside Test.startTest() and Test.stopTest() have new set of Salesforce Governor Limits. As a good practice, make sure initializing the variables, fetching records, creating and updating records are coded before Test.startTest() and Test.stopTest() and calling the controllers for code coverage is done inside Test.startTest() and Test.stopTest(). The code before Test.startTest() and after Test.stopTest() have new set of Salesforce Governor Limits and code between Test.startTest() and Test.stopTest() have new set of Salesforce Governor Limits.

Sample Test Class:

private class TestClass {
static testMethod void test() {
/*
Declare the variables, Fetch the required records, Create and update sample records
*/

/*
Test.startTest();
/*
Call the controller for code coverage
*/
Test.stopTest();
*/
}
}

How to avoid particular block of code to be avoided by test class in Salesforce?

Test.isRunningTest() is used to define whether the code is executed by test class.

Sample Code:

if(!Test.isRunningTest()) {
……………………………..
……………………………..
……………………………..
}

Syntax for test class in Salesforce

@isTest
private class class_Name{
static testMethod void method_Name(){
}
}

*Classes defined with the isTest annotation don’t count against your organization limit of 3,000,000 characters for all Apex codes. Individual methods defined with the isTest annotation do count against your organization limits.

How code coverage is calculated in Salesforce?

Code coverage is calculated by dividing the number of unique Apex code lines executed during your test method execution by the total number of Apex code lines in all of your triggers and classes. (Note: these numbers do not include lines of code within your testMethods).

The test methods must provide at least 75% code coverage to move from sandbox to production.

Use the below link to find the overall code coverage

http://www.infallibletechie.com/2014/04/how-to-see-overall-code-coverage-in.html

How to get the selected records from the related list?

StandardSetController is used to get the selected records from the related list.

Visualforce page:

Controller:

public class InterestEditExt {
public interestEditExt(ApexPages.StandardSetController controller) {
controller.setPageSize(10);
}
}

How to write test code coverage for private methods in Salesforce?

TestVisible annotation allow test methods to access private or protected members of another class outside the test class. These members include methods, member variables, and inner classes.

Sample Class:

public class TestVisibleExample {
// Private member variable
@TestVisible private static Integer recordNumber = 1;

// Private method
@TestVisible private static void updateRec() {
}
}

Test Class:

@isTest
private class TestVisibleExampleTest {
@isTest static void test1() {
// Accessing private variable annotated with TestVisible
Integer i = TestVisibleExample.recordNumber;
System.assertEquals(1, i);

// Accessing private method annotated with TestVisible
TestVisibleExample.updateRecord();
}
}

How to see the overall code coverage in Salesforce.com?

Go to Setup –> Apex Classes –> Estimate your organization’s code coverage.

How to write a test class for a controller which gets id from the url?

Sample Code:

Account acct = new Account(Name = ‘Test’);
insert acct;

apexpages.currentpage().getparameters().put(‘Aid’ , acct.Id);
Class_Name controller = new Class_Name() ;

Getting Null values from Custom Settings in Test class in Salesforce

Use (seealldata=true) to avoid null values from Custom Settings in Test class in Salesforce.

Syntax:

@isTest(seealldata=true)
public class testClass {
static testMethod void test() {
Test.StartTest();
/*…………..
…………..*/
Test.stopTest();
}
}

Test class for Schedulable class in Salesforce

@istest
public with sharing class SampleTest {
static testmethod void testSample() {
Test.startTest();
Datetime dt = Datetime.now().addMinutes(1);
String CRON_EXP = ‘0 ‘+ dt.minute() + ‘ * ‘ + dt.day() + ‘ ‘ + dt.month() + ‘ ? ‘ + dt.year();
String jobId = System.schedule(‘Sample_Heading’, CRON_EXP, new Schedulable_Class() );
Test.stopTest();
}
}

Code Coverage in Salesforce Testing
1. Go to Developer Console.

2. Go to Test –> New Run.

3. Select the Test class and click “Run” button to run the test.

Test class for Batch Apex in Salesforce

When testing your batch Apex, you can test only one execution of the execute method. You can use the scope parameter of the executeBatch method to limit the number of records passed into the execute method to ensure that you aren’t running into governor limits.

The executeBatch method starts an asynchronous process. This means that when you test batch Apex, you must make certain that the batch job is finished before testing against the results. Use the Test methods startTest and stopTest around the executeBatch method to ensure it finishes before continuing your test. All asynchronous calls made after the startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously. If you don’t include the executeBatch method within the startTest and stopTest methods, the batch job executes at the end of your test method for Apex saved using Salesforce.com API version 25.0 and later, but not in earlier versions.

Starting with Apex saved using Salesforce.com API version 22.0, exceptions that occur during the execution of a batch Apex job that is invoked by a test method are now passed to the calling test method, and as a result, causes the test method to fail. If you want to handle exceptions in the test method, enclose the code in try and catch statements. You must place the catch block after the stopTest method. Note however that with Apex saved using Salesforce.com API version 21.0 and earlier, such exceptions don’t get passed to the test method and don’t cause test methods to fail.

Sample Test Class:

@isTest
public class SampleTest {
public static testMethod void testBatch() {
Test.StartTest();
Batch_Class_Name obj = new Batch_Class_Name();
ID batchprocessid = Database.executeBatch(obj );
Test.StopTest();
}
}

Test Class for Static Method in Apex in Salesforce

@isTest
private class testClass
{
static testMethod void test()
{
Member__c m = new Member__c();
m.Name = ‘Sample’;
m.Email_Address__c = ‘[email protected]’;
m.Age__c = 25;
insert m;
memberApproval.callApproval(m.Id);
}
}

here memberApproval is an Apex class and callApproval is a static method.

**To call a static method in a test class, we have to use class name instead of object of that class.

How to test static methods in Salesforce?
To test static methods in Salesforce, we have to call the method along with the controller name, not with the object of the controller.

Example:

Apex Class:

public class example
{
public static integer add(integer a, integer b)
{
return (a+b);
}

static testMethod void testforExample()
{
example.add(8,9);
}
}

what is the use of SeeAllData=true in isTest?

In test class and methods, we can access data in the organization. Prior to it we can just access test data. Using this we can access organization data.
For Apex code saved using Salesforce.com API version 24.0 and later, use the isTest(SeeAllData=true) annotation to grant test classes and individual test methods access to all data in the organization, including pre-existing data that the test didn’t create.
Starting with Apex code saved using Salesforce.com API version 24.0, test methods don’t have access by default to pre-existing data in the organization. However, test code saved against Salesforce.com API version 23.0 or earlier continues to have access to all data in the organization and its data access is unchanged.

Unit Testing for Triggers
Sample Trigger:

trigger DuplicateMemberCheck on Member__c (before insert)
{
for(Member__c memb:trigger.new)
{
List mem = new List();

String email = memb.E_Mail_Id__c;

String sql = ‘SELECT E_Mail_Id__c FROM Member__c’;
mem = Database.Query(sql);

for(Member__c tempMember:mem)
{
if(tempMember.E_Mail_Id__c == email)
{
memb.E_Mail_Id__c.addError(‘Duplicate Record’);
}
}
}
}

Sample Test Class for Sample Trigger:

@isTest

public class TestDuplicateMemberCheckClass
{
static testMethod void test()
{
Date birthday = Date.valueOf(‘2000-12-20’);

Member__c mem = new Member__c(Name = ‘Test’, E_Mail_Id__c = ‘[email protected]’, Mobile_Number__c = ‘99966663322’, Birthday__c = birthday);

Member__c mem1 = new Member__c(Name = ‘Test’, E_Mail_Id__c = ‘[email protected]’, Mobile_Number__c = ‘99966663322’, Birthday__c = birthday);

try
{
insert mem;
insert mem1;
}
catch(DMLException e)
{
System.assert(e.getMessage().contains(‘Duplicate Record’));
}
}
}

Cheers!!!

Oh hi there 👋
It’s nice to meet you.

Sign up to receive awesome content in your inbox, every month.

We don’t spam! Please check your mail for confirmation.

Leave a Comment

Your email address will not be published. Required fields are marked *

Select Language »