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){
accIds.add(acc.Id);
}
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];
if(oppList.size()>0){
for(Opportunity opp : oppList){
if(opp.CreatedDate<day30 && opp.StageName != 'Closed Won'){
opp.StageName = 'Closed Lost';
opp.CloseDate = System.today();
oppListToUpdate.add(opp);
}
}
}
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.