I am trying to test a trigger which is as follows: When an account is updated, if more than 30 days passed after the created date of the child opportunities and stage is not "Closed Won", it should update such opportunities as "Closed Lost".

Here is my trigger:

trigger AccountTrigger on Account (after update) {
    if(Trigger.isAfter && Trigger.isUpdate){
        Set<Id> accIds = new Set<Id>();
        for(Account acc : Trigger.new){
          DateTime day30 = System.now()-30;
          List<Opportunity> oppListToUpdate=new List<Opportunity>();
          List<Opportunity> oppList = [SELECT Id, AccountId, StageName, CreatedDate, CloseDate FROM Opportunity WHERE AccountId in :accIds];
            for(Opportunity opp : oppList){
                if(opp.CreatedDate<day30 && opp.StageName != 'Closed Won'){
                    opp.StageName = 'Closed Lost';
                    opp.CloseDate = System.today();
       update oppListToUpdate;

Trigger works fine. But When I try to test it, I cannot create an account with an opportunity that has the created date of 30 days past. It creates a new opp with today's created date. When I try to use existing opps or accouts, SOQL queries do not work in the test object. I couldn't figure it out. I will appreciate any help on test of this trigger.

1 Answer 1


As long as you are not using the @seeAllData=true option on your test class/method, You can use the Test.setCreatedDate method on your newly created test opportunity record.

Hope it helps.

  • That didn't come to my mind. Let me try. Thanks a lot. Commented Sep 30, 2022 at 9:29
  • This method helped me to solve the issue. Thank you very much. I appreciate your help. Commented Oct 2, 2022 at 15:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .