• Ruben Ortiz 3
  • 5 Points
  • Member since 2014

  • Chatter
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
  • 2
In this apex class the logic is to update a custom lead field with a math.random() value.
public class leadRandomNumber {
	/* update lead status for leads related to the tasks */
    public static void updateRandomNumber (List<Lead> leadsFromTasks) {
    	system.debug ('***** entering method leadRandomNumber.updateRandomNumber class *****');
    	List<Lead> leadsToUpdate = new List<Lead>();
    	List<Lead> leads = new List<Lead>([select Id, RandomNumber__c from Lead where Id IN :leadsFromTasks and Status='Attempting' and createddate = this_year and RandomNumber__c = null]);
    	system.debug('updateRandomNumber leads queried:' + leads.size());
    	// for leads related to the tasks apply a random number to the leads if they do not yet have one
    	for(lead ld: leads) {
    		if(ld.RandomNumber__c == null) {
    			Double rand = math.random();
    			ld.RandomNumber__c = rand;
		update leadsToUpdate;
		system.debug('updateRandomNumber leadsToUpdate: ' + leads.size());

This unit test verifies that inserting the task causes the logic in the apex class above to run and update the leads as expected.
- For leads whose lead status was just updated as the result of an attempting call
- check that the random number was set
private class leadRandomNumberTest {

    static testMethod void insertAttemptingCall() {
    	system.debug('Inserting outbound preview call tasks as a new logo rep...');
    	User newLogoRep = [select id from user where isactive = true and profile.name = 'Inside Sales User' limit 1];
    	QueueSobject smbQueue = [select queue.id from queuesobject where queue.name = 'SMB AE Queue'];
    	Lead l = new Lead(Company='Company',LastName='Test',Phone='8885551234',Status='Open',LeadSource='Marketing', ownerid=smbQueue.queue.id);
        insert l;
        // bulk insert a list of calls related to the lead
        Task task = new Task(WhoId=l.Id, OwnerId=newLogoRep.Id, Type = 'Call', Five9__Five9CallType__c='Outbound Preview', Subject='Call Attempting', Status='Completed', Five9__Five9SessionId__c='fb3636336363', ActivityDate=date.today(), Five9__Five9HandleTime__c = '00:01:59', Five9__Five9WrapTime__c = '00:00:29');
        system.RunAs(newLogoRep) {
        	insert task;
        system.debug('Asserting that the leads status was updated to Attempting and it now has a RandomNumber value...');
        Task insertedTask = [select Id, Status from Task where Id =: task.id];
        // check that the lead was updated as expected
        Lead insertedLead = [select Id, Status, RandomNumber__c from Lead where Id =: l.Id];
    	system.debug('random number set to: ' + insertedLead.RandomNumber__c);

However the test coverage for the apex class is only 56% as the updates inside the for loop are not covered.

code that needs coverage

What is the best practice for test coverage for the lines that are missing?