We are implementing an override of the close date functionality. By default, opportunities that are closed and have a close date set to the future get their close date set to today. We want this to hold true for all opportunities except for opportunities of a specific record type. So I wrote a trigger to persist the original close date for these opportunities.
However I am struggling to get this functionality to work in a test. My first assertion throws an error that the close date is not being changed.
Assertion Failed: Expected: 2019-07-01 00:00:00, Actual: 2019-07-06 00:00:00
I have verified that when I first close the opportunity the not persisting
debug is printed. I've also verified there are no other triggers/workflows affecting this process.
Why is the close date not changing as it should?
Trigger:
public static void persistOriginalCloseDate(Map<Id, Opportunity> opps, Map<Id, Opportunity> oldOpps) {
Id maintenanceRecordTypeId = [SELECT Id FROM RecordType WHERE SObjectType = 'Opportunity' AND DeveloperName = 'Maintenance_Renewal'].Id;
for (Opportunity opp : opps.values()) {
Opportunity oldOpp = oldOpps.get(opp.Id);
if (opp.RecordTypeId == maintenanceRecordTypeId && opp.IsWon == true && oldOpp.IsWon == false && opp.CloseDate != oldOpp.CloseDate) {
opp.CloseDate = oldOpp.CloseDate;
System.debug('persisting');
} else {
System.debug('not persisting');
}
}
}
Test:
@IsTest
static void persistOriginalCloseDateTest() {
Account a = [SELECT Id FROM Account WHERE Name = :ACCOUNT_NAME];
Opportunity opp = new Opportunity();
opp.Name = 'Test Opportunity';
opp.CloseDate = Date.today().addDays(5);
opp.StageName = 'Active';
opp.AccountId = a.Id;
insert opp;
Test.startTest();
opp.StageName = 'Won';
update opp;
opp = [SELECT Id, CloseDate, StageName, RecordTypeId FROM Opportunity WHERE Id = :opp.Id];
System.assertEquals(Date.today(), opp.CloseDate);
opp.RecordTypeId = [SELECT Id FROM RecordType WHERE SObjectType = 'Opportunity' AND DeveloperName = 'Maintenance_Renewal'].Id;
opp.StageName = 'Active';
opp.CloseDate = Date.today().addDays(1);
update opp;
opp.StageName = 'Won';
update opp;
opp = [SELECT Id, CloseDate FROM Opportunity WHERE Id = :opp.Id];
System.assertEquals(Date.today().addDays(1), opp.CloseDate);
Test.stopTest();
}
before
the field is presented to the trigger or after the transaction commit?OpportunityTrigger on Opportunity trigger event AfterUpdate|__sfdc_trigger/OpportunityTrigger
, which is called after my before triggerSystem.runAs
in the test to get a new transaction. Thank you.System.runAs
does not work in my test. I should state, my current trigger works as intended. I am only asking for how to get the CloseDate that salesforce's trigger sets.