1

I have below trigger code :

trigger updateopportunities on Account(after update) 
{
    Set<Id> accountIds = new Set<Id>();
    for(Account ac : Trigger.new)
    {
        if(ac.Status__c=='Cancelled')
            accountIds.add(ac.id);
    }
    List<Opportunity> oppsToUpdate = new List<Opportunity>();
    for(Opportunity opp : [select id, StageName from Opportunity where AccountId in: accountIds])
    {
         opp.StageName='Closed - Cancelled';
         oppsToUpdate.add(opp);
    }
    update oppsToUpdate;
}

And below is one of the Test Method for single record testing

@isTest
Public Class TestAccountOpportunity{
    public static testMethod void verify(){
        List<Account> accounts = new List<Account>{};
        Account a = new Account(Name = 'Test Account');
        insert a;
        Opportunity opp =new opportunity(Name='TestOpportunity',accountid=a.id,StageName='Prospecting',CloseDate=system.today(),Amount=1000);
        insert Opp; 
        a.status__c = 'Cancelled';    
        update a;
        system.assertequals(opp.stageName,'Closed - Cancelled');
    }
}

The expected output as per trigger should be the stage value of Opportunity is 'Closed - Cancelled' . But System.assertequals still shows it as 'Prospecting' only. Any idea on whats going wrong.

3

You need to reselect the Opportunity before you can do an assert. Otherwise it will still hold the old values.

a.Status__c = 'Cancelled';    
update a;
System.AssertEquals('Closed - Cancelled', [SELECT StageName FROM Opportunity WHERE Id = :opp.Id].StageName);

Side note: please flip your asserts. The expected value comes first.

2

You would need to requery your Opportunity after the update, the opp you have in memory is what you had set prior to the update.

So, you should do this prior to your assert:

opp = [Select StageName From Opportunity Where Id = :opp.Id];

Then do your assert which checking the opp after it was updated in the Database.

1

In your test method the Opportunity record has the values you have set during creation. In order to retrieve the updated values (after the trigger execution) you need a SoQL query.

update a;

opp = [SELECT id, stageName From Opportunity WHERE Id = :opp.Id];

system.assertequals(opp.stageName,'Closed - Cancelled');

Then the assertion should be ok

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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