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
34213421 

How to extend code coverage for ContactHistory class with old and New Values

I have an apex class which looks for the old and new values of contacthistory. I am writing a test class for this, but could not write data to Oldvalue and Newvalue. I also tried updating the field which is tracked in history, but that gives null value when I tried assert statement. Here is my class
for(ContactHistory ct: scope){ if((ct.NewValue =='Test Data' && ct.OldValue =='Old Data')|| (ct.NewValue == 'New Test Data' && ct.OldValue =='Old Data Listing'){ //do something }}


How do I cover this if condition?
Here is my test class:
Test.startTest();
 Contact c = new contact(lastname = 'test', email='email@email.com'); 
c.TrackedField__c ='OldData'; 
c.AccountId = acc.Id; 
insert c; 
c.TrackedField__c ='Test Data';
 update c; 
Test.stopTest(); 
ContactHostory ch =[select contactid, OldValue, NewValue from ContactHistory where ContactId=: c.id and Field ='TrackedField__c' limit1];   //this is returning zero results

 
Boss CoffeeBoss Coffee
For a sanity check, could you try putting a space in between 'Old' and 'Data' in your test class? Same with Line 9 for ContactHistory.
// Change to the following
c.TrackedField__c = 'Old Data';
...
// And following misspell possible?
ContactHistory ch = [...etc];
34213421
I tried editing it, but somehow the only option I have is deleting it instead of editing.
Boss CoffeeBoss Coffee
Yeah, if you're talking about your forum post, I don't believe they let you edit it. Does that mean it's not like that in your actual org?
34213421
Yes, I am able to compile the code. The typo is just for this post
Boss CoffeeBoss Coffee
Because the records aren't actually committed, it doesn't seem to write to the history table in test classes, so that may be the reason it is returning zero results. In order to test that specific line of code, you may need to look into using test.loadData to load History records that has ParentId, OldValue, and NewValue that are not null.
34213421
I tried test.loaddata too. Looks like that is not supported for standard History Objects