+ Start a Discussion
RaoSRaoS 

Test class coverage is 54% only

//Here is my Apex class
trigger updateContactStatusToRecycle on Opportunity (After update) {
    //If a Contact is attached to an opportunity that then gets closed, Change status to Recycled only if there are no other open opportunities related to that same contact. 
    List<Id> lstOpportunityIdsToUpdate=new List<Id>();  
    
    //Select the list of opportunities
    for(Opportunity optyObj : Trigger.new)
    {
        if ((optyObj.Stagename=='Closed Won' || optyObj.Stagename=='Closed Lost') && 
            (optyObj.Stagename !=trigger.oldMap.get(optyObj.Id).Stagename)){
                lstOpportunityIdsToUpdate.add(optyObj.Id);
            }
    }
    //select the list of contact Ids that needs update
    List<Id> contactIds=new List<Id>();
    for (OpportunityContactRole ocrObj : [select Id, ContactId,Contact.Status__c, opportunityId from OpportunityContactRole where OpportunityId in :lstOpportunityIdsToUpdate ])
    {    if(ocrObj.Contact.Status__c!='Recycle'){
        contactIds.add(ocrObj.ContactId);

    }   
    }
    //seect the list of opportunities that are in '' stage
    Map<string, List<OpportunityContactRole>> oppToContactRoleMap=new Map<string, List<OpportunityContactRole>>();
    for (OpportunityContactRole ocrObj : [SELECT Id,OpportunityId,Opportunity.Id,Opportunity.StageName,  ContactId FROM OpportunityContactRole where ContactId in :contactIds and Opportunity.StageName = 'Prospecting'])
    {
        if(oppToContactRoleMap.get(ocrObj.ContactId)!=null){
            List<OpportunityContactRole> existingRecords=  oppToContactRoleMap.get(ocrObj.ContactId);
            existingRecords.add(ocrObj);
            oppToContactRoleMap.put(ocrObj.ContactId, existingRecords);
        }else{
            oppToContactRoleMap.put(ocrObj.ContactId, new List<OpportunityContactRole>{ocrObj});
        }

    }
    //Identify the Contacts whose status needs to be updated
    List<contact> lstContactsToUpdate=new List<contact>();
    for(string contactId: contactIds){
        if(oppToContactRoleMap.get(contactId)==null || oppToContactRoleMap.get(contactId).size()==0){
            lstContactsToUpdate.add(new contact(Id=contactId, Status__c = 'Recycle',Recycle_Reason__c='Cleanup'));
        }

    }
    //update the Contact status
    if(lstContactsToUpdate.size()>0){
        update lstContactsToUpdate;
    }

}

//---------------------------------------------------------------------------------
//The lines that are marked in bold are not covered by the test class
//My test class code is :
@IsTest
public class updateContactStatusToRecycleTest {
   static testMethod void updateContactStatusToRecycleTest()
    {   
        Profile p = [ Select Id, Name from Profile where name='Sales Ops Admin' limit 1 ];
        User standardSales = new User(profileId = p.id, username ='standarduserAdmin@peak.com', email = 'standarduser123@peak.com', 
                                     emailencodingkey = 'UTF-8', localesidkey ='en_US', languagelocalekey = 'en_US', timezonesidkey = 'America/Los_Angeles',
                                    alias='nuser123', lastname='lastname123');
        insert standardSales;
        system.runAs(standardSales)
        {
            Account a=new Account(Name='Test',BillingCountry='United States',BillingState='Indiana');
            insert a;
            
            Contact c=new Contact(LastName='Test',FirstName='Test', Status__c='Prospect',AccountId=a.Id, MailingCountry='United States',MailingState='Indiana');
            insert c;
            
            Opportunity op=new Opportunity(Name = 'testOpp', AccountId=a.Id,Primary_Servicing_Branch1__c='a0840000005X9TH', StageName = 'Prospecting',CloseDate = System.today(), CurrencyIsoCode = 'USD');
            insert op;
            
            op.StageName = 'Closed Won';
            Update op;
            //lstOpportunityIdsToUpdate.add(op.Id);            
            OpportunityContactRole oc=new OpportunityContactRole();
            oc.OpportunityId=op.Id;
            oc.ContactId=c.Id;
            oc.IsPrimary = TRUE;
            oc.Role = 'Decision Maker';

            insert oc;
            
            c.Status__c='Recycle';
            c.Recycle_Reason__c='Cleanup';
            Update c;
            
            Account a1=new Account(Name='Test1',BillingCountry='United States',BillingState='Indiana');
            insert a1;
            
            Contact c1=new Contact(LastName='Test1',FirstName='Test',Status__c='Prospect', AccountId=a1.Id, MailingCountry='United States',MailingState='Indiana');
            insert c1;
            
            //c1.Status__c='Recycle';
            //c1.Recycle_Reason__c='Cleanup';
            //Update c1;
            
            Opportunity op1=new Opportunity(Name = 'testOpp1', AccountId=a1.Id,Primary_Servicing_Branch1__c='a0840000005X9TH', StageName = 'Prospecting',CloseDate = System.today(), CurrencyIsoCode = 'USD');
            insert op1;
            
            op1.StageName = 'Closed Lost';
            op1.Competitor_lost_to__c='Test';
            op1.Reason_Lost__c='Pricing';
            op1.NextStep='test';
            op1.Forecast_Category2__c='Closed Lost';
            op1.Reason_Detail__c='test';
            Update op1;
            
            OpportunityContactRole oc1=new OpportunityContactRole();
            
            oc1.OpportunityId=op1.Id;
            oc1.ContactId=c1.Id;
            oc1.IsPrimary = FALSE;
            oc1.Role = 'Decision Maker';
            insert oc1;
            //lstOpportunityIdsToUpdate.add(op1.Id);            
  
            //update lstOpportunityIdsToUpdate;
        }
        
    }
}

Let me know what else am I missing which is causing the coverage to be only 54%.

Thanks
Rao
Best Answer chosen by RaoS
Payal Popat 27Payal Popat 27
You are updating opportunity "op1" before creating record in OpportunityContactRole, due to which your for loop on OpportunityContactRole will never execute and lstContactsToUpdate will always have size as zero.

All Answers

Payal Popat 27Payal Popat 27
You are updating opportunity "op1" before creating record in OpportunityContactRole, due to which your for loop on OpportunityContactRole will never execute and lstContactsToUpdate will always have size as zero.
This was selected as the best answer
RaoSRaoS
Thank you Payal.  Your suggestion has helped me to increase the test coverage to 75%. 

Even though it increased the coverage it is still not covering the lines of code that are starting with " if(oppToContactRoleMap.get(ocrObj.ContactId)!=null){"
in my Apex class.