Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

My test does:

Opportunity opp2 = opps.get(1);
opp2.probability = 40;

opp2.probability = 30;

System.debug('****opp2History=' + opp2.OpportunityHistories);

I was expecting OpportunityHistories to have some values but it is blank, since I have changed the Opportunity.

Any tips?

share|improve this question
up vote 1 down vote accepted

You need to query the database to see such changes ;)

System.debug([SELECT Id, Name FROM OpportunityHistory WHERE OpportunityId = :opp2.Id]); for a start?

I'm not sure if it will work in an unit test though (should work if you have a normal Apex Script with Execute Anonymous)... from what I remember field history tracking changes are written only when transaction actually commits and tests never commit to the database...

share|improve this answer
correct. OpportunityHistory never updated in database in test. Any other ideas? – dublintech Jan 8 '13 at 16:40
Why do you need the history values? It's a standard functionality, doesn't make much sense to check if the history really was written. If your update would fail on some trigger - you'd know because you'd get an exception. If you're afraid some workflow has overwritten the values - query the Probability from DB and assert that they're equal... – eyescream Jan 8 '13 at 16:48
I have some business logic based on the OpportunityHistory and I want to test it. – dublintech Jan 8 '13 at 17:02
I'm afraid you'll have to mock it then - create a fake List<OpportunityHistory> fakeResults variable and then if(Test.isRunningTest()){ /* use fakeResults */ } else { /* not in unit tests so query for the real data */ }. You don't even have to insert them (and probably it'd fail if you'd try it). – eyescream Jan 8 '13 at 17:09
thanks but that approach is limited because OpportunityHistory fields are not writable. So you'd have to create a wrapper around it which is so messy. Think it just won't get tested. – dublintech Jan 8 '13 at 17:23

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.