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
Lorant DobrondiLorant Dobrondi 

Code coverage for LeadHistory object

Hello,

I've made an Apex class that runs through the current weeks active leads and creates an Excel (.csv) report on the lead data + history data (looking for the dates when the status of the lead has changed from one to the next).

The code works nicely, but now when I got into the test coverage part, I was quickly surprised to see that the LeadHistory object is not working in the test classes.

The test coverage starts to be red on the following line, and I actually think that it goes into the catch(Exception) part.
 
list<LeadHistory> leadHistory = [SELECT LeadId, CreatedDate, Field, toLabel(OldValue), toLabel(NewValue) FROM LeadHistory WHERE LeadId =: l.Id AND Field = 'Status' order by CreatedDate asc];

My test class looks like this:
@isTest

public class CreateAutomaticLeadReportTest {
    static testMethod void testMethod1() {

        //create test leads
        Lead l = new Lead();
        l.LastName = 'Test John';
        l.Company = 'Testing Company';
        l.Email = 'test@email.com';
        l.Date__c = Date.newInstance(2019, 3, 1);
        l.Country__c = 'Germany';
        INSERT l;
        
        Leadhistory lh = new Leadhistory(Field='Status', LeadId=l.id);
        INSERT lh;

        Test.startTest();
            CreateAutomaticLeadReport CALR = new CreateAutomaticLeadReport();
            Database.QueryLocator ql = CALR.start(null);
            List<Lead> listOfLeads = [SELECT Id FROM Lead];
            CALR.execute(null, listOfLeads);
            CALR.Finish(null);
        Test.stopTest();
        
    }
}

I tried adding the (SeeAllData=true) annotation to my test class, but it didn't help. (Then I removed the test data insertion)​​​​​​​
BALAJI CHBALAJI CH
Hi Lorant,

Try updating the Lead instead of creating LeadHitory records. 
Please see below updated code:
@isTest

public class CreateAutomaticLeadReportTest {
    static testMethod void testMethod1() {

        //create test leads
        Lead l = new Lead();
        l.LastName = 'Test John';
        l.Company = 'Testing Company';
        l.Email = 'test@email.com';
        l.Date__c = Date.newInstance(2019, 3, 1);
        l.Country__c = 'Germany';
        l.status = 'Open - Not Contacted';
        INSERT l;
        
        l.status = 'Working - Contacted';
        Update l;

        Test.startTest();
            CreateAutomaticLeadReport CALR = new CreateAutomaticLeadReport();
            Database.QueryLocator ql = CALR.start(null);
            List<Lead> listOfLeads = [SELECT Id FROM Lead];
            CALR.execute(null, listOfLeads);
            CALR.Finish(null);
        Test.stopTest();
        
    }
}

Let us know if this works for you.


Best Regards,
​​​​​​​BALAJI