function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
rrobertsrroberts 

How to write test cases for LeadHistory?

Hi all,

 

I'm a long time developer, but new to Apex.  I've written an Apex scheduler class that counts LeadHistory fields to determine what to do with the Lead.  I'm now in the testing stage, but the more I research, the more I find that test cases are impossible (?!) for History tables.

 

My sandbox has no leads, etc in it, so I add the leads in the test cases and immediately change a value, hoping that will create LeadHistory entries, but it doesn't seem to:

 

insert new Lead(Company = 'Lead Company', FirstName = 'firstname', LastName = 'lastname');
Lead l = [select id from Lead Limit 1];
l.OwnerId = '005a0000008V0qDAAS';
update l;

 The assert comes back with LeadHistory being empty...

 

Is it really impossible to write tests for my code?  How am I supposed to test and deploy the code then?

 

Edit: I got the info that it's impossible from several forum posts, such as:
http://boards.developerforce.com/t5/Apex-Code-Development/Code-coverage-for-History-class/m-p/323429/thread-id/57307

Best Answer chosen by Admin (Salesforce Developers) 
Vinit_KumarVinit_Kumar

Robert,

 

You can create a LeadHistory record in your Test class by using the below code :-

 

 


Leadhistory lh = new Leadhistory(Field='<API namwe of field on history tracking is enabled>',LeadId=l.id);
insert lh;

 

Now,you can use the above in your assert.

 

All Answers

Vinit_KumarVinit_Kumar

Robert,

 

You can create a LeadHistory record in your Test class by using the below code :-

 

 


Leadhistory lh = new Leadhistory(Field='<API namwe of field on history tracking is enabled>',LeadId=l.id);
insert lh;

 

Now,you can use the above in your assert.

 

This was selected as the best answer
SunilKumar.ax1648SunilKumar.ax1648

@isTest

 

public class testClassName{

 

 public static testMethod void testMethod()

{

 

  

   Lead l  l =  new Lead();

   l.Name = 'name';

   insert l;

   yourClass classRef   = new YourClass();

   

ApexPages.currentPage().getHeaders().put('referer', 'l.id');

 classRef .urMethod();

}

}

rrobertsrroberts

I don't know why all those other forum posts claimed it wasn't possible.  Thanks - glad to see it's just a simple Insert, just as the Lead was.

 

Randall

rrobertsrroberts
Followup question: CreatedDate is a system field, and is read-only. How can I insert LeadHistory fields that would be from a different date? eg: a month ago, a year ago?