Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 21

Test Classes:

=============
Upon implementing the application features, we are preparing a collection of
Business Logic Functionalities in the form of "Apex Classes, Triggers, Batch
Classes, Schedule Classes, VF Controller Classes, WebServices and API's".

Once the features has been implemented, then as a Developer it is our


responsibility that we have to test each piece of business logic by using unit
testing.

We can test the features by preparing the Automated Scripts by using Apex
Programming which are called as "Test Classes".

Upon Deploying the code to the "Production Instance / Server", we have to


maintain min. 75% of the Quality Code. Else Production server doesn't allow you to
deploy the code.

By using Test Classes, we can maintain the Code Quality (Code Coverage), so
that it should not impact on the Cloud.

Note:
Upon moving the code from SandBox to SandBox, code coverage is not
required. But while moving the code from SandBox to Production, we have to maintain
min. 75% of the Code Coverage.

Note:
Each Trigger should have min. 1% of Code Coverage. Else we can't deploy
to production.

Note: Test Classes should be prepared for th below Business Logic Components.

Apex Classes
Triggers
Batch Classes
Schedule Classes
VF Controller Classes
WebServices / API's.

Note: For the Configuration features, we no need to prepare the Test Classes.

Before moving the code, we have to estimate the Organization's Code Code as
below.

Setup --> Build --> Develop.


1. Click on "Apex Classes" link.
2. Click on the link "Estimate the Organization's Code Coverage".

We can verify each Business Logic Class / Trigger Code Coverage by using the
below navigation.

Setup --> Build --> Develop


1. Click on "Apex Classes" link.
2. Open any of the Apex Class / Trigger. (Ex: CommonUtility
Class)
3. View the Field "Code Coverage". (Ex: 20%)

We can see all the Code Components Code coverage at one place by using the
below navigation.
Goto Your Name and expand it (Ex: Training Batch)
1. Click on "Developer Console" link.
2. Goto the Developer Console Editor.
3. Expand the TabBar.
4. Click on the "Tests" Tab.
5. View the Code Coverage of all the Apex Classes, Triggers at
one place in the form of a Tabular format.

Note:
For each Trigger and Business Logic Class, we have to prepare a
separate Test Class.

Upon preparing the Test Class, we have to follow the below naming
conventions / coding standards.

Ex:
Business Logic Class Name: AccountsHelper
Test Class Name: AccountsHelperTest

Business Logic Class Name: AccountsHelper


Test Class Name: AccountsHelper__Test

Business Logic Class Name: AccountsHelper


Test Class Name: TestAccountsHelper

Business Logic Class Name: AccountsHelper


Test Class Name: Test__AccountsHelper

Note:
Commented Lines of Code and Test Class Code characters will not be
counting as part of our Organization's Apex Characters Limit.

Test Class should be always pre-fixed with the annotation "@isTest".


Which indicates, that it is a Test Class.

Note:
Test Class Access specifier should be always either "Private / Public".

Upon preparing the Test Class, we have to follow the below steps.

Step 1: Prepare a Test Class withe the required name and make sure the class
should be pre-fixed with the annotation "@isTest".

Syntax:
@isTest
[Private / Public] Class <TestClassName>
{
// Write the Code to Test the Business Logic..
}

Ex:
@isTest
Private Class AccountsHelperTest
{
// Write the Testing Code..
}

@isTest
Private Class AutoLeadConvertTriggerTest
{
// Write the Testing Code..
}

Step 2: Prepare the Test Method inside the Test Class. Which will invoke
automatically upon testing the business logic.

Rules:
1. Test method should be always a "Static" method.
2. Test Method doesn't return any value to the calling
environment.
Hence the return type should be always "Void".
3. Test Method should be always defined by using the keyword
"testmethod".
4. We can call / invoke the normal / business methods from the
TestMethod.

Syntax:
Static testmethod void <MethodName>()
{
// Write the Testing Code..
}

Ex:
@isTest
Private Class AccountsHelperTest
{
static testmethod void TestAccountsLogic()
{
// Write the Testing Code..
}
}

Step 3: Invoke the Test Class / Run the Test Class.

Standard Navigation:
Setup --> Build --> Develop --> Apex Classes.
Open the Test Class.
1. Click on "Run Test" button.

Standard Navigation:
Setup --> Build --> Develop
1. Click on "Apex Test Execution" link.
2. Select the Test Classes by using the "CheckBoxes".
3. Click on "Run Test" button.

Standard Navigation:
Setup --> Build --> Develop
1. Click on "Apex Classes" link.
2. Click on "Run All Test" button.

Developer Console:
Open the Developer Console.
1. Create the Test Class.
2. Write the Code inside the Test Class.
3. Save the Class Code by using "CTRL+S".
4. Click on "Run Test" button.

UseCase:
========
Create an Apex Class to perform the Mathematical Operations and Prepare the
Test Class to test the Business Logic.

Class Code:
-----------
public class MathOperationsUtility
{
Public static void Addition(integer x, integer y, integer z)
{
system.debug('Addition Result : '+ (x + y + z));
}

Public static void Multiply(integer x, integer y)


{
system.debug('Multiply Result is....: '+ (x * y));
}

Public static void Division(integer x, integer y)


{
system.debug('Division Result is....: '+ (x / y));
}

Public static void Modulus(integer x, integer y)


{
system.debug('Reminder Value is....: '+ Math.mod(x, y));
}
}

Test Class Code:


----------------
@isTest
Private class MathOperationsUtilityTest
{
static testmethod void TestMathOperations()
{
// Invoke the Business Logic Methods..
MathOperationsUtility.Addition(100,4500,500);

MathOperationsUtility.Multiply(20000, 400);

MathOperationsUtility.Division(4500, 20);

MathOperationsUtility.Modulus(400,6);
}
}

UseCase:
========
Write an apex class, to Prepare a collection of Functions to be used to
perform the Mathematical Operations and String Operations. And write the Test Class
for the Business Logic.

Class Code:
-----------
public class CommonUtilityHandler
{
Public static integer Addition(integer x, integer y)
{
return (x + y);
}

Public static integer Multiply(integer x, integer y, integer z)


{
return (x * y * z);
}

Public static Boolean CheckEquals(string s1, string s2)


{
if(s1 == s2)
return true;
else
return false;
}

Public static Boolean CheckEqualsWithCase(string s1, string s2)


{
return s1.equals(s2);
}

Public static string Concatenate(string s1, string s2)


{
return s1 + s2;
}
}

Test Class Code:


----------------
@isTest
private class CommonUtilityHandlerTest
{
static testmethod void TestCommonMethods()
{
system.assertEquals(550, CommonUtilityHandler.Addition(100, 450));
system.assertEquals(20450 , CommonUtilityHandler.Addition(20000, 450));

system.assertEquals( 4500,CommonUtilityHandler.Multiply(10, 45, 10));

system.assertEquals(true, CommonUtilityHandler.CheckEquals('Welcome',
'Welcome'));
system.assertEquals(true, CommonUtilityHandler.CheckEquals('Welcome',
'welcome'));
system.assertEquals(false, CommonUtilityHandler.CheckEquals('Welcome',
'Welcome1')); // Negative Case;

system.assertEquals(true,
CommonUtilityHandler.CheckEqualsWithCase('Welcome','Welcome'));
system.assertEquals(false,
CommonUtilityHandler.CheckEqualsWithCase('Welcome','welcome')); // Negative Case;

system.assertEquals('HelloWelcome',
CommonUtilityHandler.Concatenate('Hello','Welcome'));
}
}

UseCase:
========
Prepare the Test Class for the Trigger, Which Auto Converts the Lead as the
Customer upon updating the Status as "Closed - Converted".

Trigger Code:
-------------
trigger AutoLeadConvertTrigger on Lead (After Update, Before Insert)
{
if(Trigger.isAfter && Trigger.isUpdate)
{
LeadHandlerUtility.AfterUpdate(Trigger.New);
}

if(Trigger.isBefore && Trigger.isInsert)


{
LeadHandlerUtility.BeforeInsert(Trigger.New);
}
}

Handler Class:
--------------
public class LeadHandlerUtility
{
Public static void AfterUpdate(List<Lead> lstLeads)
{
LeadStatus lStatus = [Select id, MasterLabel, isConverted
from LeadStatus
Where isConverted = true];

List<Database.LeadConvert> lstConvert = new List<Database.LeadConvert>();

for(Lead ldRecord : lstLeads)


{
if(ldRecord.Status == 'Closed - Converted' && ldRecord.IsConverted ==
false)
{
Database.LeadConvert lConvert = new Database.LeadConvert();

lConvert.setLeadId(ldRecord.Id);

lConvert.setDoNotCreateOpportunity(ldRecord.Do_Not_Create_Opportunity__c);

lConvert.setSendNotificationEmail(true);

lConvert.setConvertedStatus(lStatus.MasterLabel);

// Add the record to Collection..


lstConvert.Add(lConvert);
}
}

if(! lstConvert.isEmpty())
{
Database.LeadConvertResult[] result = Database.convertLead(lstConvert,
false);
}
}

Public static void BeforeInsert(List<Lead> lstLeads)


{
// Write the Valdiations / Business Logic..
}
}

Test Class Code:


----------------
@isTest
public class AutoLeadConvertTriggerTest
{
static testmethod void TestAutoLeadConversionProcess()
{
// Creating a Lead Record..
Lead ldRecord = new Lead();
ldRecord.FirstName = 'Test ';
ldRecord.LastName = 'Lead Record';
ldRecord.Company = 'Testing';
ldRecord.Title = 'Sales Head';
ldRecord.Email = 'testing@test.com';
ldRecord.Phone = '9900998877';
ldRecord.Fax = '9900887755';
ldRecord.Rating = 'Hot';
ldRecord.Industry = 'Banking';
ldRecord.PAN_Number__c = 'ALPPB8989R';
ldRecord.Passport_Number__c = 'ALPPB8989R';
ldRecord.Do_Not_Create_Opportunity__c = false;
ldRecord.AnnualRevenue = 3400000;
ldRecord.Status = 'Open - Not Contacted';
ldRecord.City = 'Hyderabad';

insert ldRecord;

// Update the Lead Record..


ldRecord.Status = 'Closed - Converted';

update ldRecord;
}
}

UseCase:
========
Prepare the Test Class for the Batch Classes by providing the required Test
Data.

Hiring ManagerBatch Class:


--------------------------
Global class HiringManagerUpdateBatch implements Database.Batchable<SObject>
{
Global Database.QueryLocator Start(Database.BatchableContext bContext)
{
string hrRecordsQuery = 'Select id, name, location__C, contact_number__C,
email_id__C from Hiring_Manager__C';
return Database.getQueryLocator(hrRecordsQuery);
}

Global void Execute(Database.BatchableContext bContext, List<SObject>


recordsToProcess)
{
if(! recordsToProcess.isEmpty())
{
List<Hiring_Manager__C> hrRecordsToUpdate = new
List<Hiring_Manager__C>();
List<ID> hrRecordsToDelete = new List<ID>();

for(SObject obj : recordsToProcess)


{
Hiring_Manager__C hrRecord = (Hiring_Manager__C) obj;

if(hrRecord.Email_ID__c != null)
{
hrRecord.Location__c = 'Hyderabad';
hrRecord.Contact_Number__c = '5555888899';

hrRecordsToUpdate.Add(hrRecord);
}
else
{
hrRecordsToDelete.Add(hrREcord.Id);
}

if(! hrRecordsToUpdate.isEmpty())
{
Update hrRecordsToUpdate;
}

if(! hrRecordsToDelete.isEmpty())
{
Database.delete(hrRecordsToDelete);
}
}
}

Global void Finish(Database.BatchableContext bContext)


{
System.debug('Batch Job Id is....: '+ bContext.getJobId());

AsyncApexJob jobDetails = [Select id, status, totaljobItems,


jobitemsprocessed,
numberoferrors, createdby.email
from AsyncApexJob
Where id =: bContext.getJobId()];

MessagingUtilityHelper.SendBatchJobStatusNotifications(jobDetails,'HiringManagerUpd
ateBatch');
}
}

Calculate Annual Revenue Batch Class:


-------------------------------------
Global class CalculateTotalAnnualRevenueBatch implements
Database.Batchable<SObject>, Database.Stateful
{
Global Decimal totalAnnualRevenue = 0.0;

Global Database.QueryLocator Start(Database.BatchableContext bContext)


{
string accountsQuery = 'Select id, name, annualrevenue from Account where
annualrevenue != null';
return Database.getQueryLocator(accountsQuery);
}

Global void Execute(Database.BatchableContext bContext, List<SObject>


accountsToProcess)
{
if(! accountsToProcess.isEmpty())
{
for(SObject obj : accountsToProcess)
{
Account acc = (Account) obj;

totalAnnualRevenue += acc.AnnualRevenue;
}
}
}

Global void Finish(Database.BatchableContext bContext)


{
system.debug('Batch Job Id is.....: '+ bContext.getJobId());

AsyncApexJob jobDetails = [Select id, status, totaljobItems,


jobItemsProcessed,
NumberOfErrors, CreatedBy.Email
from AsyncApexJob
Where id =:
bContext.getJobId() ];

MessagingUtilityHelper.SendTotalRevenueJobStatusNotification(jobDetails,
'CalculateTotalAnnualRevenueBatch', totalAnnualRevenue);
}
}

MessagingUtility Class:
-----------------------
public class MessagingUtilityHelper
{
Public static void SendTotalRevenueJobStatusNotification(AsyncApexJob jobInfo,
string jobName, Decimal revenueAmount)
{
if(jobInfo != null)
{
Messaging.SingleEmailMessage email = new
Messaging.SingleEmailMessage();

string[] toAddress = new string[]{jobInfo.CreatedBy.Email};


email.setToAddresses(toAddress);

email.setReplyTo('customersupport@dell.com');

email.setSenderDisplayName('DELL Weekly Batch Job Support Team');

string emailSubject = 'Alert : Customers Total Annual Revenue Batch


Job Status Notification: '+ jobName + ' - ( '+ jobInfo.Id+ ' )';
email.setSubject(emailSubject);
string emailContent = 'Dear Customer Support, <br/><br/> We are
pleased to inform you that we have executed the Customers Total Annual Revenue
Calculation Batch Job. <br/><br/>'+
'Please find below the Batch Job Status Details....:
<br/><br/>'+
'Batch Job Id .......: ' + jobInfo.Id+
'<br/> Batch Job Name ......: '+ jobName+
'<br/> Batch Job Status .......: '+ jobInfo.Status+
'<br/> Total Number of Batches ......: '+
jobInfo.TotalJobItems+
'<br/> Number of Batvhes Processed .....: '+
jobInfo.JobItemsProcessed+
'<br/> Number of Batches Failed.........: '+
jobInfo.NumberOfErrors+
'<br/> Total Annual Revenue is..........: '+
revenueAmount+
'<br/><br/> Please find the below address, if any
queries. '+
'<br/><br/> <i> *** This is a System Generated Email.
Please Do Not Reply.</i>'+
'<br/><br/> Thanks & Reagrds, <br/> Customer Support
Team, <br/> Dell Inc. ';
email.setHtmlBody(emailContent);

Messaging.SendEmailResult[] results = Messaging.sendEmail(new


Messaging.SingleEmailMessage[]{email});
}
}

Public static void SendBatchJobStatusNotifications(AsyncApexJob jobInfo, string


jobName)
{
if(jobInfo != null)
{
Messaging.SingleEmailMessage email = new
Messaging.SingleEmailMessage();

string[] toAddress = new string[]{jobInfo.CreatedBy.Email,


'yamini.segu@gmail.com','msoni.janghel@gmail.com'};
email.setToAddresses(toAddress);

email.setReplyTo('customersupport@dell.com');

email.setSenderDisplayName('DELL Weekly Batch Job Support Team');

string emailSubject = 'Alert : Hiring Manager Weekly Batch Job Status


Notification: '+ jobName + ' - ( '+ jobInfo.Id+ ' )';
email.setSubject(emailSubject);

string emailContent = 'Dear Customer Support, <br/><br/> We are


pleased to inform you that we have executed the Weekly Hiring Manager Update Batch
Job. <br/><br/>'+
'Please find below the Batch Job Status Details....:
<br/><br/>'+
'Batch Job Id .......: ' + jobInfo.Id+
'<br/> Batch Job Name ......: '+ jobName+
'<br/> Batch Job Status .......: '+ jobInfo.Status+
'<br/> Total Number of Batches ......: '+
jobInfo.TotalJobItems+
'<br/> Number of Batvhes Processed .....: '+
jobInfo.JobItemsProcessed+
'<br/> Number of Batches Failed.........: '+
jobInfo.NumberOfErrors+
'<br/><br/> Please find the below address, if any
queries. '+
'<br/><br/> <i> *** This is a System Generated Email.
Please Do Not Reply.</i>'+
'<br/><br/> Thanks & Reagrds, <br/> Customer Support
Team, <br/> Dell Inc. ';
email.setHtmlBody(emailContent);

Messaging.SendEmailResult[] results = Messaging.sendEmail(new


Messaging.SingleEmailMessage[]{email});
}
}
}

Test Class:
-----------
@isTest
public class HiringManagerUpdateBatchTest
{
static testmethod void TestHiringManagerBatch()
{
CreateHiringManagerRecords();

CreateBulkAccountRecords();

// Test the Batch Class..

Test.startTest();

HiringManagerUpdateBatch hrBatch = new HiringManagerUpdateBatch();


Database.executeBatch(hrBatch);

CalculateTotalAnnualRevenueBatch accountsBatch = new


CalculateTotalAnnualRevenueBatch();
Database.executeBatch(accountsBatch);

Test.stopTest();
}

// Method for Test Data Preparation..


Public static void CreateHiringManagerRecords()
{
List<Hiring_Manager__C> lstHrRecords = new List<Hiring_Manager__C>();

for(integer counter = 1; counter <= 100; counter++)


{
Hiring_Manager__C hr = new Hiring_MAnager__C();

hr.Name = 'Test - '+ counter;


hr.Location__c = 'Mumbai';
hr.Email_ID__c = 'testhr'+counter+'@gmail.com';
hr.Contact_Number__c = '9900665544';

lstHrRecords.Add(hr);
}
if(! lstHrRecords.isEmpty())
{
insert lstHrRecords;
}
}

// Method to Prepare the Account Records..


Public static void CreateBulkAccountRecords()
{
List<Account> lstAccounts = new List<Account>();

for(integer counter = 1; counter <= 50; counter++)


{
Account acc = new Account();

acc.Name = 'Parent Test Account';


acc.Rating = 'Hot';
acc.Industry = 'Banking';
acc.AnnualRevenue = 2500000;
acc.Type = 'Prospect';
acc.Phone = '9900887766';
acc.fax = '9900556677';
acc.website = 'www.salesforce.com';
acc.BillingCity = 'Hyderabad';
acc.BillingState = 'Telangana';
acc.BillingCountry = 'India';
acc.CustomerPriority__C = 'High';
acc.Active__C = 'Yes';

lstAccounts.Add(acc);
}

if(! lstAccounts.isEmpty())
{
insert lstAccounts;
}
}
}

UseCase:
========
Create a Test Class for the "Future Method", which will create a Hiring
Manager Record inside the object.

Future Method Class:


--------------------
public class CommonHelper
{
Public static void DoDMLOperations()
{
// De-Activate the User Record.. (Setup Object)
User userToDeActivate = [Select id, username, isActive
from User
Where username = 'testing330@gmail.com'
Limit 1];

if(userToDeActivate.id != null)
{
userToDeActivate.IsActive = false;

update userToDeActivate;

// Invoke the Method to Create HR Record..


CreateHRRecord();
}
}

@future()
Public static void CreateHRRecord()
{
// Create a Hiring Manager Record.. (Non-Setup Object)
Hiring_Manager__C hrRecord = new Hiring_Manager__C();

hrRecord.Name = 'Sudeep Kumar';


hrRecord.Location__c = 'Mumbai';
hrRecord.Contact_Number__c = '9988554411';
hrRecord.Email_ID__c = 'sudeep@gmail.com';

insert hrRecord;
}
}

Test Class:
-----------
@isTest
public class TestCommonHelper
{
static testmethod void TestFutureMethod()
{
CommonHelper.DoDMLOperations();
}
}

UseCase:
========
Prepare the Test Class for the Queueable Classes.

HiringManager Queueable Class:


------------------------------
Global class HiringManagerQueueable implements System.Queueable
{
Global void Execute(System.QueueableContext qContext)
{
// Write the Business Logic to Insert the Hiring Manager Record..
Hiring_Manager__C hrRecord = new Hiring_Manager__C();
hrRecord.Name = 'Praveen Kumar';
hrRecord.Location__c = 'Chennai';
hrRecord.Contact_Number__c = '8899554433';
hrRecord.Email_ID__c = 'praveen@gmail.com';

insert hrRecord;
if(hrRecord.Id != null)
{
system.debug('Hiring Manager Record ID is...: '+ hrRecord.id);

// Invoke the PositionQueueable class to Create the Related


Position Record.
ID posJobId = System.enqueueJob(new PositionsQueueable(hrRecord));

}
}
}

PositionQueueable Class:
------------------------
Global class PositionsQueueable implements System.Queueable
{
/*
* 1. Constructor Name should be always same as the Class Name.
* 2. Constructors are used to assign the default values for the class
members.
* 3. Constructor should be always defined with "Public" access specifier.
* 4. Constructor doesn't have any return type even void.
* 5. Constructor can have one or more parameters.
*/

Hiring_Manager__C hrRecord;

Public PositionsQueueable(Hiring_Manager__C hr)


{
hrRecord = hr;
}

Global void Execute(System.QueueableContext qContext)


{
// Write the Code to Create a Related Position Record..
Position__C pos = new Position__C();

pos.Name = 'Salesforce Marketing Cloud Consultant';


pos.Location__c = hrRecord.Location__c;
pos.Position_Status__c = 'New Position';
pos.Number_of_Positions__c = 2;
pos.Open_Date__c = system.today();
pos.Milestone_Date__c = system.today().AddDays(30);
pos.HR_Contact_Number__c = hrRecord.Contact_Number__c;
pos.HR_Email_ID__c = hrRecord.Email_ID__c;
pos.Minimum_Budget__c = 1400000;
pos.Maximum_Budget__c = 1800000;
pos.Passport_Required__c = true;
pos.Travel_Required__c = true;
pos.Position_Description__c = 'Required 2+ years of experience in
Salesforce Marketing Cloud.';
pos.Skills_Required__c = 'Required 2+ years experience in Email Studio,
Journey Builder, Content Builder, Mobile Studio.';

// Make the Position To be Related to HR.


pos.HiringManager__c = hrRecord.Id;

insert pos;
if(pos.Id != null)
{
system.debug('Position Record Inserted with id...: '+ pos.Id);
}
}
}
Test Class:
-----------
@isTest
public class HiringManagerQueueableTest
{
static testmethod void TestQueueableClasses()
{
HiringManagerQueueable hrQueueable = new HiringManagerQueueable();

hrQueueable.Execute(null);
}
}

UseCase:
========
Prepare the Test Class to Test the Apex Sharing Process by using Invocable
Methods.

Invocable Method Code:


----------------------
public class AccountsShareHandler
{
@InvocableMethod(Label='Share Account Record' Description='This method will
Share the Account Record to Specified User.')
Public static void AfterInsert(List<Account> lstAccounts)
{
if(! lstAccounts.isEmpty())
{
List<AccountShare> shareAccountRecords = new List<AccountShare>();

for(Account acc : lstAccounts)


{
if(acc.Share_Record_To_User__c != null)
{
// Prepare the Share Details..
AccountShare accShare = new AccountShare();

accShare.AccountId = acc.Id;
accShare.UserOrGroupId = acc.Share_Record_To_User__c;
accShare.RowCause = 'Manual';
accShare.OpportunityAccessLevel = 'READ';
accShare.CaseAccessLevel = 'READ';

if(acc.AnnualRevenue >= 5000000)


accShare.AccountAccessLevel = 'EDIT';
else
accShare.AccountAccessLevel = 'READ';

// Add the Record to Collection for Bulkification..


shareAccountRecords.Add(accShare);
}
}

if(! shareAccountRecords.isEmpty())
{
Insert shareAccountRecords;
}
}
}
}

Test Class Code:


----------------
@isTest
Private class AccountsShareHandlerTest
{
static testmethod void TestAccountShareProcess()
{
// Write the Code to Insert Bulk Accounts..
List<Account> lstAccounts = new List<Account>();

for(integer counter = 1; counter <= 5; counter++)


{
Account acc = new Account();
acc.Name = 'Test Account - '+ counter;
acc.Rating = 'Hot';

if(counter >= 3)
acc.AnnualRevenue = 5700000;
else
acc.AnnualRevenue = 4400000;

acc.Industry = 'Banking';
acc.Phone = '9900998877';
acc.Fax = '9988776655';
acc.Website = 'www.gmail.com';
acc.Type = 'Prospect';
acc.Active__c = 'Yes';
acc.CustomerPriority__c = 'High';
acc.Ownership = 'Public';
acc.Share_Record_To_User__c = CreateUserRecord();

lstAccounts.Add(acc);
}

if(! lstAccounts.isEmpty())
{
Insert lstAccounts;

// Supply the Records to the Method.


AccountsShareHandler.AfterInsert(lstAccounts);
}
}

Public static ID CreateUserRecord()


{
// Write the Code to Insert a New User Record..

User testUser = new User();

testUser.ProfileId = [Select id from Profile where name= 'System


Administrator'].id;
testUser.FirstName = 'Sample';
testUSer.LastName = 'TestUser';
testUser.Email = 'testUser@test.com';
testUser.Username = 'testuser@test.com'+system.currentTimeMillis();
testUser.CompanyName = 'Test';
testUser.Title = 'Test User';
testUser.Alias = 'testaias';
testUser.TimeZoneSidKey = 'America/Los_Angeles';
testUser.EmailEncodingKey = 'UTF-8';
testUser.LanguageLocaleKey = 'en_US';
testUser.LocaleSidKey = 'en_US';

insert testUSer;

return testUSer.Id;
}
}

UseCase:
========
Prepare a Test Class for the below Visualforce Controller.

VF Page Code:
-------------
<apex:page controller="ShowAccountRecordsController" setup="false" sidebar="false"
showheader="true" tabStyle="Position__c" >
<apex:sectionHeader title="Accounts" subtitle="All Accounts"/>
<apex:form >
<apex:pageblock title="Account Records : ( {!lstAccounts.size} )">

<apex:pageblockTable value="{!lstAccounts}" var="acc">


<apex:column value="{!acc.Name}"/>
<apex:column value="{!acc.Rating}"/>
<apex:column value="{!acc.industry}"/>
<apex:column value="{!acc.Annualrevenue}"/>
<apex:column value="{!acc.Phone}"/>
<apex:column value="{!acc.Fax}"/>
<apex:column value="{!acc.Active__c}"/>
</apex:pageblockTable>

</apex:pageblock>
</apex:form>
</apex:page>

Controller Class:
-----------------
public class ShowAccountRecordsController
{
Public List<Account> lstAccounts{get;set;}

// Prepare a Default Constructor..


Public ShowAccountRecordsController()
{
lstAccounts = new List<Account>();

lstAccounts = [Select id, name, rating, industry, annualrevenue, active__C,


Phone, fax, website
from Account
Order by name];
}
}

Test Class:
-----------
@isTest
private class ShowAccountRecordsControllerTest
{
static testmethod void TestAccountsController()
{
// Create the Account Records..
CreateAccounts();

//Invoke the Controller Class..


ShowAccountRecordsController accController = new
ShowAccountRecordsController();
}

Public static void CreateAccounts()


{
// Write the Code to Insert Bulk Accounts..
List<Account> lstAccounts = new List<Account>();

for(integer counter = 1; counter <= 50; counter++)


{
Account acc = new Account();
acc.Name = 'Test Account - '+ counter;
acc.Rating = 'Hot';

if(counter >= 3)
acc.AnnualRevenue = 5700000;
else
acc.AnnualRevenue = 4400000;

acc.Industry = 'Banking';
acc.Phone = '9900998877';
acc.Fax = '9988776655';
acc.Website = 'www.gmail.com';
acc.Type = 'Prospect';
acc.Active__c = 'Yes';
acc.CustomerPriority__c = 'High';
acc.Ownership = 'Public';

lstAccounts.Add(acc);
}

if(! lstAccounts.isEmpty())
{
Insert lstAccounts;
}
}
}

UseCase:
========
Prepare the Test Class for the Visualforce Controller Class, which is used to
Search for the Accounts based on the Search Text.

VF Page Code:
-------------
<apex:page controller="SearchRecordsController" setup="false" sidebar="false"
showHeader="true" tabStyle="Customer__c" >
<apex:sectionHeader title="Accounts" subtitle="Search Accounts"/>
<apex:form >
<apex:Pageblock title="Search Accounts Block">
<apex:pageblocksection title="Search Acounts Section" columns="2"
collapsible="false">
<apex:inputtext label="Enter Search Text : " html-placeholder="Enter
Search Text" value="{!searchText}"/>
<apex:commandButton value="Search Accounts" action="{!
SearchAccountRecords}" rerender="pgBlock" />
</apex:pageblocksection>
</apex:Pageblock>

<apex:pageblock title="Search Results : ( {!lstAccounts.size} )"


id="pgBlock">

<apex:pageblockTable value="{!lstAccounts}" var="acc">


<apex:column headerValue="Account Name">
<apex:outputlink value="/{!acc.id}" target="_blank"> {!acc.Name}
</apex:outputlink>
</apex:column>
<apex:column value="{!acc.Rating}"/>
<apex:column value="{!acc.Industry}"/>
<apex:column value="{!acc.Annualrevenue}"/>
<apex:column value="{!acc.Type}"/>
<apex:column value="{!acc.Phone}"/>
<apex:column value="{!acc.Fax}"/>
<apex:column value="{!acc.Active__c}"/>
</apex:pageblockTable>

</apex:pageblock>
</apex:form>
</apex:page>

Controller Class:
-----------------
public class SearchRecordsController
{
Public string searchText{get;set;}
Public List<Account> lstAccounts{get;set;}

Public void SearchAccountRecords()


{
lstAccounts = new List<Account>();

if(searchText != null && searchText != '')


{
lstAccounts = [Select id, name, rating, industry, annualrevenue, phone,
fax, type, ownership, active__C
from Account
Where name like : searchText+'%' ];
}
}
}

Test Class:
-----------
@isTest
Private class SearchRecordsControllerTest
{
static testmethod void TestSearchController()
{
// Insert the Account Records (Prepare Test Data)
CreateAccounts();

//Test the Controller Class.


SearchRecordsController accountsController = new SearchRecordsController();

// supply the values..


accountsController.searchText = 'Test';
// Invoke the Controller Method..
accountsController.SearchAccountRecords();
}

Public static void CreateAccounts()


{
// Write the Code to Insert Bulk Accounts..
List<Account> lstAccounts = new List<Account>();

for(integer counter = 1; counter <= 50; counter++)


{
Account acc = new Account();
acc.Name = 'Test Account - '+ counter;
acc.Rating = 'Hot';

if(counter >= 3)
acc.AnnualRevenue = 5700000;
else
acc.AnnualRevenue = 4400000;

acc.Industry = 'Banking';
acc.Phone = '9900998877';
acc.Fax = '9988776655';
acc.Website = 'www.gmail.com';
acc.Type = 'Prospect';
acc.Active__c = 'Yes';
acc.CustomerPriority__c = 'High';
acc.Ownership = 'Public';

lstAccounts.Add(acc);
}

if(! lstAccounts.isEmpty())
{
Insert lstAccounts;
}
}
}

You might also like