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
Vishnu7700Vishnu7700 

Test coverage for .addError and .add statments in trigger

Hi can any one help me out to get test coverage for .addError and .add statments

Below is the trigger and test calss.

Bold line are not covered with the existing test class.

trigger Erroriftwoopportunityareopen on Opportunity (before insert) {

 

    Set <id> setAccWithProspectingOpp = new Set <Id>();//Varaible to hold Account with Prospecting opp

    Set <id> setAccId = new Set <Id>();//Varaible to hold Account IDs

   

    if(trigger.isbefore){

        if(trigger.isinsert){

            //Iterate through opportunity

            for(Opportunity o:Trigger.new){

                //System.debug('Account Id -->'+o.Accountid);

                //Verify account id not null and opportunity stagename is Prospecting

                if(o.Accountid != Null && o.StageName == 'Prospecting'){

                    setAccId.add(o.Accountid);//Account is added to setAccId(Varaible)

                }

            }

            //System.debug('Set of accounts -->'+setAccId);

            //Fetch the accounitid of opportunity from aetAccId(Varaible)

            for(Opportunity Opp : [Select id,accountid from opportunity where accountid in :setAccId]){

                setAccWithProspectingOpp.add(Opp.accountid);//Add opportunity account id in setAccWithProspectingOpp(Variable)

            }

            //System.debug('Set of accounts with Prosp Opp-->'+setAccWithProspectingOpp);

            //Iterate through opportunity object

            for(Opportunity o:Trigger.new){

                //Chack condition that in setAccWithProspectingOpp(Varaible)contains opportunity account id

                if(setAccWithProspectingOpp.contains(o.accountid))

                    o.addError('This account already has Opportunity with StageName as Prospecting');  

            }

           

        }

    }

}

Test class

@isTest

    public class ErroriftwoopportunityareopenTest{

        static testMethod void Test(){

        User thisUser = [ Select Id from User where Id = :UserInfo.getUserId() ];

        Account acc = new Account(Name = 'TestAccount',Rating = 'Hot',Type = 'Prospect');

            //update acc;

        Opportunity opp = new Opportunity(Name = 'TestOpp',Accountid = acc.Id,CloseDate = Date.Today(),StageName = 'Prospecting');

            //update opp;

        Opportunity opp1 = new Opportunity(Name = 'TestOpp1',Accountid = acc.Id,CloseDate = Date.Today(),StageName = 'ClosedWon');

            //update opp1;

        Opportunity opp2 = new Opportunity(Name = 'TestOpp2',Accountid = acc.Id,CloseDate = Date.Today(),StageName = 'ClosedLost');

            //update opp2;

        Task t = new Task(WhatId=acc.Id,WhoId = opp.Id,Subject = 'Email',Status = 'Completed', Priority ='Normal');

            insert t;

        Test.startTest();

            insert acc;

            insert opp;

            insert opp1;

            insert opp2;

             User someOtherUser = [Select Id From User Where Id != :UserInfo.getUserId() And isActive = TRUE LIMIT 1];

    system.runAs(someOtherUser){

          insert opp;

     }

        Test.StopTest();

        }

    }

Best Answer chosen by Admin (Salesforce Developers) 
amilawamilaw

 Opportunity opp = new Opportunity(Name = 'TestOpp',Accountid = acc.Id,CloseDate = Date.Today(),StageName = 'Prospecting');

at the time you are inserting above opportunity, there are no any other opportunities in DB. 

 

try inserting opp1 before opp

All Answers

amilawamilaw

place the  insert acc; just after you initialized acc object. before initializing opportunities.

to cover add error, you will have to have a try catch block in your test clas. otherwise test will fail as exception is thrown from add error

Vishnu7700Vishnu7700

Hi,

followed as you said now i got only 83% coverage

and now

setAccWithProspectingOpp.add(Opp.accountid);//Add opportunity account id in setAccWithProspectingOpp(Variable)o.addError('This account already has Opportunity with StageName as Prospecting');

 

above two line are not covered.

amilawamilaw

 Opportunity opp = new Opportunity(Name = 'TestOpp',Accountid = acc.Id,CloseDate = Date.Today(),StageName = 'Prospecting');

at the time you are inserting above opportunity, there are no any other opportunities in DB. 

 

try inserting opp1 before opp

This was selected as the best answer
Vishnu7700Vishnu7700
Thanks for help.....achived 100% code coverage.
Assigned Kodos for u.
Vishnu7700Vishnu7700

Hi ,

A quick question

can you please let me know how to get code coverage forbelow line

If(setOppIds.size()>0){
            //Fetch list of task associated with opportunity stored in setOppIds varaible
            lsttask = [Select id, Status from Task where WhatId in :setOppIds];
                if(lsttask.size()>0){
                    for(Task tsk : lsttask){
                        tsk.Status = 'Completed';
                    }
                    update lsttask;
                }
        }

Test code

:i had written is

Opportunity opp2 = new Opportunity(Name = 'TestOpp2',Accountid = acc.Id,CloseDate = Date.Today(),StageName = 'ClosedLost');
            insert opp2;
        Task t = new Task(Subject = 'Sample Test',WhatId=opp2.Id,Type = 'Email',Status = 'Completed', Priority ='Normal',ActivityDate =Date.Today());
            update t;

 

can you please help me out this.

amilawamilaw

  update t; should be insert t;.

if your code is from opportunity trigger, check whether trigger is marked for after update. and update the opportunity after inserting task

Vishnu7700Vishnu7700

Hi,

Modified code as u said but still task realted cose was not covered.

amilawamilaw

post the full code of the trigger

Vishnu7700Vishnu7700
 trigger MultipleRealScenariostrigger on Opportunity (before insert, before update, before delete, after update ){
         //varaibles hold open and closed types StageName
         Set<string> openstages = new Set<string>();
         Set<string> closedstages = new Set<string>();
        
        //Add open stages in the set
        openstages.add('Prospecting');
        openstages.add('Qualification');
        openstages.add('Needs Analysis');
        openstages.add('Value Proposition');
        openstages.add('Id. Decision Makers');
        openstages.add('Perception Analysis');
        openstages.add('Proposal/Price Quote');
        openstages.add('Negotiation/Review');
        //Add close stages in the set
        closedstages.add('Closed Won');
        closedstages.add('Closed Lost');
        
        //Get list of opp with stagename as Prospecting and userinfo
        List<Opportunity> opplist = [Select id from opportunity where StageName =:'Prospecting' and StageName =:'Closed Lost' Limit 2];
        String userprofile = [Select name from profile where Id = :UserInfo.getProfileId()].name;
        List<Task> lsttask = new List<Task>();//List of Tasks
        Set<ID> setOppIds = new Set<ID>();//Holds set of opportunity Ids
        
        //Iterate through opportunity object
        for(opportunity o : Trigger.new){
            //trigger of contextvaraibles isinsert and isupdate
            if(trigger.isinsert||trigger.isupdate){
                if(trigger.isupdate){
                    //Condition to check stagename with old value if it is close can not be changed to open stage
                    if(Trigger.oldMap.get(o.Id).StageName == 'Closed' && o.StageName == 'Open'){
                        o.addError('Stage can not be move from closed to open');
                        return;
                    }
                    /*if(closedstages.contains(system.Trigger.oldMap.get(o.Id).StageName)&& openstages.contains.(o.StageName)){
                        o.adderror('Stage can not be moved back form Close to Open');
                    }*/
                }
                //Verify condition that opportunity stagename is closedLost
                if(o.StageName == 'Closed Lost' && o.StageName != Trigger.OldMap.get(o.Id).StageName){
                    setOppIds.add(o.Id);//Add opportunity ids in variable setOppIds
                }
                //Check the opplist variable size if size is greater then 1 through error
                if(opplist.size()>1){
                    o.adderror('Already one Opportunity with open status present');
                }
            
            //Trigger for context variable isupdate and isdelete    
            if(trigger.isupdate||trigger.isdelete){
                //check condition that stagename as closedlost and userprofile is sys admin
                if(o.StageName =='Closed Lost'&& userprofile !='System Administrator'){
                //Through error while user not equal to sys admin trys to delete or modify closed lost opportunity
                    o.adderror('Only Admin can delete once opportunity status is closed');
                }
            }
           }
        }  
        //if opportunity stage name is ClosedLost then associated tasks status is updated to Completed
        If(setOppIds.size()>0){
            //Fetch list of task associated with opportunity stored in setOppIds varaible
            lsttask = [Select id, Status from Task where WhatId in :setOppIds];
                if(lsttask.size()>0){
                    for(Task tsk : lsttask){
                        tsk.Status = 'Completed';
                    }
                    update lsttask; 
                }
        }
    }

 Full trigger code

amilawamilaw

when inserting opp2 set stageName to something other than "Closed Lost"

 

when updating change it to "Closed Lost"