+ Start a Discussion
sfdotcomsfdotcom 

Test Class for .addError

Hi,
Please help me on writing test class for .addError for below trigger. I am getting 100% code coverage but test methods not are getting passed. 
Thanks in advance.

Trigger:
trigger OpportunityTrigger on Opportunity (before update) {
    for(Opportunity oppty : trigger.new) {
        if(trigger.oldMap.get(oppty.Id).StageName == 'Closed Won') {
            oppty.addError('Closed Opportunity cannot be updated');
        }
    }
}

Test class: 100 % code coverage
@isTest
public class test_OpportunityTrigger {
    static testMethod void testUpdate(){
        Opportunity opp = new Opportunity(Name = 'Test', StageName = 'Closed Won', CloseDate = System.Today().addMonths(1));
        insert opp;
        opp.Name = 'Test1';
        try{
        update opp;
        }
       catch (Exception e){

        System.assert(e.getMessage().contains('Can not add'));

}
    }
}
sfdotcomsfdotcom
Hi ,I got solution
I forgot to update message.
Solutions:
System.assert(e.getMessage().contains('Closed Opportunity cannot be updated'));
Suraj Tripathi 47Suraj Tripathi 47
Hello Sfdotcom,

Whenever you perform an insert or update DML Operation, please use Database.insert(List<SObject> updatelist, false) instead of direct insert as well as Database.update.
make sure the SObject list has those records which will raise an error.

If you find your Solution then Mark this as Best Answer

Thank you!
Regards,
Suraj Tripathi