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
Gaurav Khare 16Gaurav Khare 16 

OpportunityHistory Data in Test Class

Hi , My entire application works on Opportunity history data (all batches) , There are cases like opportunites close dates changed in current month or previous month and much like this, evaluating previous one year data. I can create oppoturinity but I need its history in previous periods as well for traversing various of my If and else conditions, This seems next to impossible, I cannot use seeAllData=true, as it is a package and when installed on other system may fail. What can be the hack here?
 
Any help would be appreciated!!!
Dushyant SonwarDushyant Sonwar

Hi Gaurav,

HIstory records are not created in testclasses.(https://success.salesforce.com/ideaView?id=08730000000h6RwAAI)
you need cover that part by creating a fake history data records in your main class.

You can take idea from this below post.
http://salesforce.stackexchange.com/questions/4007/is-it-possible-to-test-apex-that-relies-on-field-history-tracking
Hope this helps.

Gaurav Khare 16Gaurav Khare 16
Thanks Dushayant for your reply, I have gone through those links .. but in my case it is not field history tracking but opportuniyHistory object where I check if hist.created date is less or greater than previous months and other similar comparisons etc. But yes to go by above approach I can create fakeHistoryObject and inserts its data in test class then in main class using isTesting populate the object accordingly i.e. List lst; if(Test.isTesting){ lst = [Select StageName__c from fakeHistoryObject] ; }else{ lst = [Select StageName__c from OpportunityHistory] } for(sObject obj : lst){ if(Test.isTesting){ if(obj.get('StageName__c) ..... }else{ if(obj.get('StageName) ..... } } It would be a lot of change as there are many batches almost 30-40 Is there any better option?
Dushyant SonwarDushyant Sonwar

You need to create fakedata in your main Class. You cannot create history records in testclass .
The approach of creating testdata for history records will be the same. 

if (Test.isRunningTest()) {

lstOpportunityHistory.add(new OpportunityHistory(...));

lstOpportunityHistory.add(new OpportunityHistory(...));

}

Gaurav Khare 16Gaurav Khare 16
Hi Dushyant , You mean I should not create custom object fakeOpportunityHistory and rather I insert data in proper OpportunityHistory object using Test.isRunningTest(). But so far I know we cannot insert data into OpportunityHistory object directly Regards Gaurav
Dushyant SonwarDushyant Sonwar

Gaurav,

You don't need to create any custom object and perform any DML.
You just need to fill the list(data) of OpportunityHistory

You can also set created date shown in below post.

http://salesforce.stackexchange.com/questions/130475/how-to-create-test-data-for-a-class-that-checks-for-historical-data

Gaurav Khare 16Gaurav Khare 16
Hi Dushyant, I am getting this error : "Save error: Field is not writeable: OpportunityHistory.OpportunityId" List lst1 = [Select Id,StageName, amount from Opportunity]; System.debug('lst1.size()--->' + lst1.size()); List lstOpportunityHistory; if (Test.isRunningTest()) { lstOpportunityHistory = new List(); lstOpportunityHistory.add(new OpportunityHistory(opportunityId = lst1[0].id, StageName = 'Value', amount = 500, CloseDate = System.Now().date().addDays(5), createdDate = System.Today() )); } System.debug('lstOpportunityHistory.size()--->' + lstOpportunityHistory.size());
Gaurav Khare 16Gaurav Khare 16
Not even for this field, for every field it is saying Save error: Field is not writeable: OpportunityHistory.StageName
Dushyant SonwarDushyant Sonwar

Try with not assigning the opportunityId , If you are using OpportunityHistory.opportunityId reference in your main Class or if there is block checking the opportunity  , then try mimicking the standard object with the modal/wrapper class. You can use below as an example to do this.

http://salesforce.stackexchange.com/questions/115664/test-class-error-compile-error-field-is-not-writeable-opportunity-connectio

Dushyant SonwarDushyant Sonwar

Hi Gaurav,

OpportunityHistory object is a read only object . Only change you can do is try with mimicking with a wrapper/modal class.

Hope this helps.

Gaurav Khare 16Gaurav Khare 16
I tried but not able to do so, but its not working, giving error Save error: Illegal assignment from List to List // Main class code: List listOppHistory = [Select OpportunityId, amount from OpportunityHistory]; if(Test.isRunningTest()){ listOppHistory = OpportunityHistoryTest.getTestOpps(); } // Mimic Class public class OpportunityHistoryTest{ public static OpportunityHistory[] getTestOpps(){ OpportunityHistory[] tmp = new OpportunityHistory[]{}; return (OpportunityHistory[])json.deserialize(json.serialize(New OpportunityHistory()),List.class); } public class OpportunityHistory{ public id id {get;set;} public String StageName {get;set;} public Date closeDate {get;set;} public OpportunityHistory(){ //name = 'test'; } } }
prathyusha nalaboluprathyusha nalabolu
Please try code like this:
Opportunity opportunity_Obj = new Opportunity(IsPrivate = false, Name = 'Name144',Account_Record_Type__c = 'Tenant', Property_Name_Text__c = 'ogcp', StageName = 'Exchanging Proposals', CloseDate = Date.today(), Budget_Confirmed__c = false, Discovery_Completed__c = false, ROI_Analysis_Completed__c = false, Additional_Approval_Required__c = false, Deal_Submitted_for_Approval__c = false, Deal_Type__c = 'New Lease', Leasing_Property_Lead__c = user_id, Property__c = propertyObj_Id, Has_Options__c = false, Highest_Active_Deal__c = false);
        Insert opportunity_Obj;
        opportunity opp=[select id,StageName from Opportunity where id=:opportunity_Obj.Id];
        opp.StageName='Fully Executed Lease';
        update opp;
Test.startTest();
OpportunityFieldHistory coh = new OpportunityFieldHistory(OpportunityId = opp.id, Field = 'StageName'); 
        insert coh; 
        String Query='SELECT id,OpportunityId,CreatedDate,oldValue,NewValue,Field from OpportunityFieldHistory';            
        ESRT_SendNotificationsOrEmailsBatch obj=new ESRT_SendNotificationsOrEmailsBatch(Query);
        DataBase.executeBatch(obj,100);
Test.stopTest();