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
Vijay NagarathinamVijay Nagarathinam 

How to query OpportunityHistory in apex test class

Hi Experts,

I am not able to query the opportunity history in a test class. If I tried to query the history, it returns null values. Please let me know how to use the opportunity history object in apex test class.

Amit Chaudhary 8Amit Chaudhary 8
use seeAllData=true. Only then you will get history record. Let us know if this will work
Vijay NagarathinamVijay Nagarathinam
Hi Amit, 

Is there any alternative option without using seeAllData = true option in test class?
N.M. SharmaN.M. Sharma
Hi Vijay,

I have try the same thing rigth now. And the conclusion is you can not query the OpportunityHistory without SeeAllData = true. Try my code once with SeeAllData = true and then SeeAllData = false and check the Debug you can easily understand what is happening behind.
public class testCls{
    static testMethod void validateHelloWorld(){
        Account testAcct = new Account (Name = 'My Test Account');
        insert testAcct;
        Opportunity oppt = new Opportunity(Name ='New mAWS Deal',
                            AccountID = testAcct.ID,
                            StageName = 'Qualification',
                            Amount = 3000,
                            CloseDate =

        insert oppt;
        oppt.StageName = 'Closed Won';
        oppt.Amount = 5000;
        Update oppt;
        list<opportunity> lstOpp = [select id, (select id from OpportunityHistories) from Opportunity where];
        system.debug('lstOpp: ' + lstOpp);  
        system.debug('lstOpp: ' + lstOpp[0].OpportunityHistories);  
        list<OpportunityHistory> oppHistoryLst = [SELECT Id, OpportunityId, CreatedById, CreatedDate, StageName, 
                                                Amount, ExpectedRevenue, CloseDate, Probability, ForecastCategory, 
                                                SystemModstamp, IsDeleted FROM OpportunityHistory where OpportunityId];
        system.debug('oppHistoryLst: ' + oppHistoryLst);