Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

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.

share|improve this question

3 Answers 3

up vote 2 down vote accepted

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.

share|improve this answer

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.

share|improve this answer

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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