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
Kevin Chiles 930Kevin Chiles 930 

Code coverage not high enough for trigger HELP!

Hello!

I have a trigger that is creating a contact role on the Opportunity when a lookup field is populated but I cannot get my code coverage above 66%!
What can I do to get better coverage?!
Trigger:
trigger addContactRole on Opportunity (after Insert, after update) {

List<OpportunityContactRole> newContactRoleList=new List<OpportunityContactRole>();
List<OpportunityContactRole> oldContactRoleList=new List<OpportunityContactRole>();
Set<Id> OppId=new Set<Id>();
Set<Id> ContactId=new Set<Id>();

for(Opportunity oppObj: Trigger.new)
{
//Insert condition
if(Trigger.isInsert)
{
if(oppObj.Investor__c!=null && Trigger.oldMap.get(oppObj.Id).Investor__c==null)
{
//Creating new contact role
newContactRoleList.add(new OpportunityContactRole (ContactId=oppObj.Investor__c,OpportunityId=oppObj.Id, Role='Decision Maker', IsPrimary = true));

}
}
else
{

if(oppObj.Investor__c==null && Trigger.oldMap.get(oppObj.Id).Investor__c!=null)
{
//Getting the contact and oppty Id from old values and adding this in set
Opportunity OldoppObj=Trigger.oldMap.get(oppObj.Id);
OppId.add(OldoppObj.id);
ContactId.add(OldoppObj.Investor__c);

}
else if(oppObj.Investor__c!=null && Trigger.oldMap.get(oppObj.Id).Investor__c==null)
{
//Creating new contact role
newContactRoleList.add(new OpportunityContactRole (ContactId=oppObj.Investor__c, OpportunityId=oppObj.Id, Role='Decision Maker', IsPrimary = true));
}
}
}


try
{
//inserting new Contacts
if(newContactRoleList.size()>0) insert newContactRoleList;

//Selecting old contact roles
if (OppId.size()>0) oldContactRoleList=[Select Id from OpportunityContactRole where ContactId in : ContactId and OpportunityId in : OppId];

//Deleting old contact roles
if (oldContactRoleList.size()>0) delete oldContactRoleList;
}
catch(Exception e)
{
System.debug(e);
trigger.new[0].addError('Technical error occurred. Please contact to your system administrator or try after some time.');

}




}

Test Class:
 
@isTest(SeeAllData=true)

public class YourTriggerTestClass{
    static testMethod void yourTestMethod(){
    
        //fill all the required field and make sure your data passes the validation rules.
        //insert account
        account acc = new account(
        Name='test account');
        
        insert acc;
        
        //insert contact
        contact ct2 = new Contact(
        LastName='Tester',
        AccountId=acc.id);
        
        insert ct2;
        
        contact ct = new Contact(
        LastName='Tester',
        AccountId=acc.id);
        
        insert ct;
        
        //insert propert
        Property__c p = new Property__c(
        Name='test');
        
        insert p;
        
        //insert campaign
        Campaign camp = new Campaign(
        Name='test camp',
        IsActive=True,
        Property__c=p.Id);
        
        insert camp;
        
        
        //Insert Opportunity
        opportunity opp = new opportunity(
        Name = 'Test oppty',
        
        CampaignId=camp.id,
        StageName='Prospecting',
        CloseDate=system.today(),
        AccountId=acc.id
        );
        
        insert opp;
        
        opp.Investor__r=ct2;
        
        update opp;
        
        
        
        }
        }

 
Best Answer chosen by Kevin Chiles 930
Donald BlayDonald Blay
Adding the following block of code towards the end of yoru test method you will get you up to 86% by satisfying the If condition at line 26. 
        opp.Investor__c=ct2.id;
        update opp;
        opp.Investor__c = null;
        update opp;

 
But I think the code at line 16 cannot be hit, it's not a scenario that will ever happen.  That block is in an if block for Trigger.isInsert (line 11).  But at line 13 you are trying to get the Opp's old value from Trigger.oldMap. Since it's an insert (the record does not exist yet) there could never be a old value.  

All Answers

Donald BlayDonald Blay
Adding the following block of code towards the end of yoru test method you will get you up to 86% by satisfying the If condition at line 26. 
        opp.Investor__c=ct2.id;
        update opp;
        opp.Investor__c = null;
        update opp;

 
But I think the code at line 16 cannot be hit, it's not a scenario that will ever happen.  That block is in an if block for Trigger.isInsert (line 11).  But at line 13 you are trying to get the Opp's old value from Trigger.oldMap. Since it's an insert (the record does not exist yet) there could never be a old value.  
This was selected as the best answer
Kevin Chiles 930Kevin Chiles 930
Thanks Donald!

So simple and yet got me where I needed to go.  I ditched the old map too as it could never work.  I think it was added in as a guard against duplicate records but its on insert, so it wouldn't create duplicates.  Thanks!
Kevin Chiles 930Kevin Chiles 930
Updated Trigger and Test Class:
 
trigger addContactRole on Opportunity (after Insert, after update) {
    
    List<OpportunityContactRole> newContactRoleList=new List<OpportunityContactRole>();
    List<OpportunityContactRole> oldContactRoleList=new List<OpportunityContactRole>();
    Set<Id> OppId=new Set<Id>();
    Set<Id> ContactId=new Set<Id>();
   
    for(Opportunity oppObj: Trigger.new)
    {
        //Insert condition    
        if(Trigger.isInsert)
        {
            if(oppObj.Investor__c!=null)
            {
                //Creating new contact role
                newContactRoleList.add(new OpportunityContactRole (ContactId=oppObj.Investor__c,OpportunityId=oppObj.Id, Role='Decision Maker',IsPrimary=True));
                                                                                         
            }
        }
        else
        {   
       
                if(oppObj.Investor__c==null && Trigger.oldMap.get(oppObj.Id).Investor__c!=null)
                {
                    //Getting the contact and oppty Id from old values and adding this in set               
                     Opportunity OldoppObj=Trigger.oldMap.get(oppObj.Id);        
                     OppId.add(OldoppObj.id);
                     ContactId.add(OldoppObj.Investor__c);
                    
                }
                else if(oppObj.Investor__c!=null && Trigger.oldMap.get(oppObj.Id).Investor__c==null)
                {
                    //Creating new contact role
                    newContactRoleList.add(new OpportunityContactRole (ContactId=oppObj.Investor__c, OpportunityId=oppObj.Id, Role='Business User',IsPrimary=True));
                }
        }                    
    }
   
   
    try
    {
        //inserting new Contact Roles
        if(newContactRoleList.size()>0) insert newContactRoleList;
       
        //Selecting old Selecting old contact roles
        if ( OppId.size()>0) oldContactRoleList=[Select Id from OpportunityContactRole where ContactId in : ContactId  and OpportunityId in : OppId];
       
        //Deleting old contact roles
        if (oldContactRoleList.size()>0) delete oldContactRoleList;
    }
    catch(Exception e)
    {
        System.debug(e);
        trigger.new[0].addError('Technical error occurred. Please contact to your system administrator or try after some time.');
       
    }
   
   
   
   
}

Test Class: Coverage at 80%
 
@isTest(SeeAllData=true)

public class YourTriggerTestClass{
    static testMethod void yourTestMethod(){
    
        //fill all the required field and make sure your data passes the validation rules.
        //insert account
        account acc = new account(
        Name='test account');
        
        insert acc;
        
        //insert contact
        contact ct2 = new Contact(
        LastName='Tester',
        AccountId=acc.id);
        
        insert ct2;
        
        contact ct = new Contact(
        LastName='Tester',
        AccountId=acc.id);
        
        insert ct;
        
        //insert propert
        Property__c p = new Property__c(
        Name='test');
        
        insert p;
        
        //insert campaign
        Campaign camp = new Campaign(
        Name='test camp',
        IsActive=True,
        Property__c=p.Id);
        
        insert camp;
        
        
        //Insert Opportunity
        opportunity opp = new opportunity(
        Name = 'Test oppty',
        
        CampaignId=camp.id,
        StageName='Prospecting',
        CloseDate=system.today(),
        AccountId=acc.id);
        opp.Investor__c=ct.Id
        ;
        
        insert opp;
        
                          
        
        //opp.Investor__c=ct2.id;
        
       // update opp;
        
        opp.Investor__c = null;

        update opp;
        
        }
        }