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
akashakash 

Help me to write test handler and test class for this trigger.

when the Account is updated check all opportunities related to the account. Update all Opportunities Stage to close lost if an opportunity created date is greater than 30 days from today and stage not equal to close won


trigger OppoStageUpdate on Account (after update){
Set<Id> accountIds = new Set<Id>();
for(Account a:Trigger.new){
accountIds.add(a.Id);
}
//day30 is the date which is 30 days less than today
DateTime day30=system.now()-30;
List<Opportunity> oppListToUpdate=new List<Opportunity>();
//getting the opportunities whose account has been updated
List<Opportunity> oppList = [Select Id, AccountId, StageName, CreatedDate, CloseDate from Opportunity where AccountId in :accountIds];
if(oppList.size()>0){
for(Opportunity opp : oppList){
//checking for condition if created date is greater than 30 days from today and stage not equal to close won
if(opp.CreatedDate<day30 && opp.StageName!='Closed Won'){
opp.StageName='Closed Lost';    //This is a mandatory field when we update the CloseDate
opp.CloseDate=system.today();
oppListToUpdate.add(opp);  //putting the changed opportunity to separate list to update later
}
}
}
//checking if the opportunity list which has changed is having records or not
if(oppListToUpdate.size()>0){
update oppListToUpdate;
}
}
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Akash,

Can you try the below test class. It gives 100% coverage.
 
@isTest
private class OppoStageUpdateTest {
    static testMethod void testOppoStageUpdate() {
        //Create test account
        Account acc = new Account();
        acc.Name = 'Test Account';
        insert acc;

        //Create test opportunity that meets the criteria
        Opportunity opp1 = new Opportunity();
        opp1.Name = 'Test Opp1';
        opp1.StageName = 'Prospecting';
        opp1.CloseDate = System.today().addDays(20);
        opp1.AccountId = acc.Id;
        insert opp1;
        Datetime yesterday = Datetime.now().addDays(-40);
        Test.setCreatedDate(opp1.Id, yesterday); 

        //Create test opportunity that does not meet the criteria
        Opportunity opp2 = new Opportunity();
        opp2.Name = 'Test Opp2';
        opp2.StageName = 'Prospecting';
        opp2.CloseDate = System.today().addDays(20);
        opp2.AccountId = acc.Id;
        insert opp2;
Datetime farway = Datetime.now().addDays(-40);
        Test.setCreatedDate(opp2.Id, yesterday); 
        //Update account to trigger the trigger
        acc.Description = 'Test Description';
        update acc;
        

        //Retrieve the updated opportunities
        List<Opportunity> updatedOpps = [SELECT Id, StageName, CloseDate FROM Opportunity WHERE Id IN :new Set<Id>{opp1.Id, opp2.Id}];

        //Assert that only opp1 was updated
        System.assertEquals(1, updatedOpps.size());
        System.assertEquals('Closed Lost', updatedOpps[0].StageName);
        System.assertEquals(System.today(), updatedOpps[0].CloseDate);
    }
}

Let me know if you face any issues.

If this solution helps, Please mark it as best answer.

Thanks,
Mohit. LakdeMohit. Lakde
trigger UpdateOpportunities on Account (after update) {

    Set<Id> updatedAccountIds = new Set<Id>();
    for (Account acc : Trigger.new) {
        if (acc.IsDeleted || Trigger.oldMap.get(acc.Id).LastModifiedDate == acc.LastModifiedDate) {
           
            continue;
        }
        updatedAccountIds.add(acc.Id);
    }

    if (updatedAccountIds.isEmpty()) {
 
        return;
    }

    // Collect all Opportunities related to updated Accounts
    List<Opportunity> opportunitiesToUpdate = new List<Opportunity>();
    for (Opportunity opp : [SELECT Id, StageName, CreatedDate FROM Opportunity WHERE AccountId IN :updatedAccountIds AND StageName != 'Close Won']) {
        if (opp.CreatedDate.daysBetween(System.today()) > 30) {
            opp.StageName = 'Close Lost';
            opportunitiesToUpdate.add(opp);
        }
    }

    if (!opportunitiesToUpdate.isEmpty()) {
        // Update all Opportunities
        update opportunitiesToUpdate;
    }
}

Hi Akash, 

Try this code (move code from Trigger to Handler as best practice, this is just sample code) and if it work, mark this as best answer