+ Start a Discussion
MedhanieHabteMedhanieHabte 

Creating a test class for an Opportunity Contact Role trigger

Greetings, I am writing a test class for a trigger that creates Opportunity Contact Roles based on the primary record. I currently have 60% code coverage and am stuck determining what steps I would need to add to achieve 75% or greater code coverage. 

Here is my trigger
trigger CreateContactRole on Opportunity (after insert, after update) {

    //get the id of all involved accounts
    Set<ID> accountIds = new Set<ID>();
    for(Opportunity opt:Trigger.New){
        accountIds.add(opt.AccountId);
    }
    
    //get all contacts for those accounts
    list<Contact> contacts = new list<Contact>();
    contacts = [select id, AccountId from Contact where AccountId in: accountIds order by createddate Limit 5000];
    
    //organize these contacts by account
    Map<Id,List<Contact>> contactsByAccount = new Map<ID,List<Contact>>();
    for(Contact c:contacts){
        if(contactsByAccount.get(c.AccountId) == null){
            contactsByAccount.put(c.AccountId,new List<Contact>());
        }
        contactsByAccount.get(c.AccountId).add(c);
    }
    
    // check to see if the Opportunity already has a contact role.  If it does, add to a set of Ids to exclude
    List<OpportunityContactRole> existingOCR = new List<OpportunityContactRole>();
    Set<Id> existingOCRIds = new Set<Id>();
    existingOCR = [select OpportunityId from OpportunityContactRole where OpportunityId in:Trigger.newMap.keySet() limit 5000];
    for(OpportunityContactRole ocr:existingOCR) if(!existingOCRIds.contains(ocr.OpportunityId)) existingOCRIds.add(ocr.OpportunityId);
    
    //create the OpportunityContactRole objects
    list<OpportunityContactRole> lstOCR = new list<OpportunityContactRole>();
    for(Opportunity opt:Trigger.New){
        if(!existingOCRIds.contains(opt.Id) && contactsByAccount.get(opt.AccountId) != null){
            Boolean firstContact = true;
            for(Contact c: contactsByAccount.get(opt.AccountId)){
                OpportunityContactRole ocr = new OpportunityContactRole(OpportunityId=opt.id, ContactId=c.id);
                if(firstContact) {
                    ocr.IsPrimary = TRUE;
                    firstContact = FALSE;
                }
                lstOCR.add(ocr);
            }
        }
    }
    insert lstOCR;
}

Here are the areas that don't appear to be covered, particularly the null pointer exception.
if(contactsByAccount.get(c.AccountId) == null){
            contactsByAccount.put(c.AccountId,new List<Contact>());
        }
        contactsByAccount.get(c.AccountId).add(c);


 
Boolean firstContact = true;
            for(Contact c: contactsByAccount.get(opt.AccountId)){
                OpportunityContactRole ocr = new OpportunityContactRole(OpportunityId=opt.id, ContactId=c.id);
                if(firstContact) {
                    ocr.IsPrimary = TRUE;
                    firstContact = FALSE;
                }
                lstOCR.add(ocr);

And here is my test class
@isTest
public class TestCreateContactRole {
    static testMethod void createAccount(){

    Account a = new Account();
    
    //First create the Account
    a.Name = 'Test Co.';
    a.BillingStreet = '298 S. Ringo Street';
    a.BillingCity = 'Little Rock';
    a.BillingState = 'AR';
    a.BillingPostalCode = '72201';
    a.BillingCountry = 'USA';
    a.Phone = '501-555-5555';
    a.Website = 'www.testco.com';
    a.Mission_Statement__c = 'We do lots of things';
    a.Facebook_URL__c = 'www.facebooktest.com';
    insert a;
    System.debug('created account');
        
    //Then create a primary contact
    Contact c = new Contact();
    c.FirstName = 'Paul';
    c.LastName  = 'Test';
    c.AccountId = a.id;
    c.MailingStreet = '298 S. Ringo Street';
    c.MailingCity = 'Little Rock';
    c.MailingState = 'AR';
    c.MailingPostalCode = '72201'; 
    c.Primary_Membership_Contact__c = TRUE;
    insert c;
    System.debug('created primary contact');
        
    //Then create another non-primary contact
    Contact ci = new Contact();
    ci.FirstName = 'Bob';
    ci.LastName  = 'Test';
    ci.AccountId = a.id;
    ci.MailingStreet = '298 S. Ringo Street';
    ci.MailingCity = 'Little Rock';
    ci.MailingState = 'AR';
    ci.MailingPostalCode = '72201'; 
    ci.Primary_Membership_Contact__c = FALSE;
    insert ci;
    System.debug('created primary contact');
        
    //Now create an opportunity
    Opportunity o = new Opportunity();
    o.RecordType = [SELECT Id, Name, DeveloperName FROM RecordType WHERE Name = 'Membership' LIMIT 1];
    o.Name = 'New Record';
    o.StageName = 'Posted';
    o.Special_Case_for_Amount_Due__c = 'No';
    o.Special_Case_for_Membership_End_Date__c = 'No';
    o.CloseDate = Date.today();
    o.npe01__Membership_Start_Date__c = Date.today();
    o.npe01__Member_Level__c = 'Nonprofit 1';
    o.Description = 'Test Record';
    insert o;
    System.debug('created opportunity');
        
    //Now update the OCR for the primary contact
    OpportunityContactRole ocr = new OpportunityContactRole();
    ocr.ContactId = c.Id;
    ocr.OpportunityId = o.Id;
    ocr.IsPrimary = TRUE;
    ocr.Role = 'Decision Maker';
    insert ocr;
    System.debug('created opportunity contact role for primary');
        
    //Now update the OCR for the non-primary contact
    OpportunityContactRole ocr1 = new OpportunityContactRole();
   	    
    ocr1.ContactId = ci.Id;
    ocr1.OpportunityId = o.Id;
    ocr1.IsPrimary = FALSE;
    ocr1.Role = 'Decision Maker';
    insert ocr1;
    System.debug('created opportunity contact role for non-primary contact');
                
}
}

I'm fairly new to Apex, but would love to learn more. Hope it helps.
Best Answer chosen by MedhanieHabte
Amit Chaudhary 8Amit Chaudhary 8
Please try below code
Try to update opportunity
@isTest
public class TestCreateContactRole {
    static testMethod void createAccount()
	{

		Account a = new Account();
		a.Name = 'Test Co.';
		a.BillingStreet = '298 S. Ringo Street';
		a.BillingCity = 'Little Rock';
		a.BillingState = 'AR';
		a.BillingPostalCode = '72201';
		a.BillingCountry = 'USA';
		a.Phone = '501-555-5555';
		a.Website = 'www.testco.com';
		a.Mission_Statement__c = 'We do lots of things';
		a.Facebook_URL__c = 'www.facebooktest.com';
		insert a;
		System.debug('created account');
			
		//Then create a primary contact
		Contact c = new Contact();
		c.FirstName = 'Paul';
		c.LastName  = 'Test';
		c.AccountId = a.id;
		c.MailingStreet = '298 S. Ringo Street';
		c.MailingCity = 'Little Rock';
		c.MailingState = 'AR';
		c.MailingPostalCode = '72201'; 
		c.Primary_Membership_Contact__c = TRUE;
		insert c;
		System.debug('created primary contact');
			
		//Then create another non-primary contact
		Contact ci = new Contact();
		ci.FirstName = 'Bob';
		ci.LastName  = 'Test';
		ci.AccountId = a.id;
		ci.MailingStreet = '298 S. Ringo Street';
		ci.MailingCity = 'Little Rock';
		ci.MailingState = 'AR';
		ci.MailingPostalCode = '72201'; 
		ci.Primary_Membership_Contact__c = FALSE;
		insert ci;
		System.debug('created primary contact');
			
		//Now create an opportunity
		Opportunity o = new Opportunity();
		o.RecordType = [SELECT Id, Name, DeveloperName FROM RecordType WHERE Name = 'Membership' LIMIT 1];
		o.Name = 'New Record';
		o.StageName = 'Posted';
		o.Special_Case_for_Amount_Due__c = 'No';
		o.Special_Case_for_Membership_End_Date__c = 'No';
		o.CloseDate = Date.today();
		o.npe01__Membership_Start_Date__c = Date.today();
		o.npe01__Member_Level__c = 'Nonprofit 1';
		o.Description = 'Test Record';
		insert o;
		System.debug('created opportunity');
			
		//Now update the OCR for the primary contact
		OpportunityContactRole ocr = new OpportunityContactRole();
		ocr.ContactId = c.Id;
		ocr.OpportunityId = o.Id;
		ocr.IsPrimary = TRUE;
		ocr.Role = 'Decision Maker';
		insert ocr;
		System.debug('created opportunity contact role for primary');
			
		//Now update the OCR for the non-primary contact
		OpportunityContactRole ocr1 = new OpportunityContactRole();
			
		ocr1.ContactId = ci.Id;
		ocr1.OpportunityId = o.Id;
		ocr1.IsPrimary = FALSE;
		ocr1.Role = 'Decision Maker';
		insert ocr1;
		System.debug('created opportunity contact role for non-primary contact');
		
		Update o;
					
	}
}

 

All Answers

MedhanieHabteMedhanieHabte
On realization, I ran all tests as opposed to running individual tests and was able to achieve 100% code coverage. This has been resolved.
Amit Chaudhary 8Amit Chaudhary 8
Please try below code
Try to update opportunity
@isTest
public class TestCreateContactRole {
    static testMethod void createAccount()
	{

		Account a = new Account();
		a.Name = 'Test Co.';
		a.BillingStreet = '298 S. Ringo Street';
		a.BillingCity = 'Little Rock';
		a.BillingState = 'AR';
		a.BillingPostalCode = '72201';
		a.BillingCountry = 'USA';
		a.Phone = '501-555-5555';
		a.Website = 'www.testco.com';
		a.Mission_Statement__c = 'We do lots of things';
		a.Facebook_URL__c = 'www.facebooktest.com';
		insert a;
		System.debug('created account');
			
		//Then create a primary contact
		Contact c = new Contact();
		c.FirstName = 'Paul';
		c.LastName  = 'Test';
		c.AccountId = a.id;
		c.MailingStreet = '298 S. Ringo Street';
		c.MailingCity = 'Little Rock';
		c.MailingState = 'AR';
		c.MailingPostalCode = '72201'; 
		c.Primary_Membership_Contact__c = TRUE;
		insert c;
		System.debug('created primary contact');
			
		//Then create another non-primary contact
		Contact ci = new Contact();
		ci.FirstName = 'Bob';
		ci.LastName  = 'Test';
		ci.AccountId = a.id;
		ci.MailingStreet = '298 S. Ringo Street';
		ci.MailingCity = 'Little Rock';
		ci.MailingState = 'AR';
		ci.MailingPostalCode = '72201'; 
		ci.Primary_Membership_Contact__c = FALSE;
		insert ci;
		System.debug('created primary contact');
			
		//Now create an opportunity
		Opportunity o = new Opportunity();
		o.RecordType = [SELECT Id, Name, DeveloperName FROM RecordType WHERE Name = 'Membership' LIMIT 1];
		o.Name = 'New Record';
		o.StageName = 'Posted';
		o.Special_Case_for_Amount_Due__c = 'No';
		o.Special_Case_for_Membership_End_Date__c = 'No';
		o.CloseDate = Date.today();
		o.npe01__Membership_Start_Date__c = Date.today();
		o.npe01__Member_Level__c = 'Nonprofit 1';
		o.Description = 'Test Record';
		insert o;
		System.debug('created opportunity');
			
		//Now update the OCR for the primary contact
		OpportunityContactRole ocr = new OpportunityContactRole();
		ocr.ContactId = c.Id;
		ocr.OpportunityId = o.Id;
		ocr.IsPrimary = TRUE;
		ocr.Role = 'Decision Maker';
		insert ocr;
		System.debug('created opportunity contact role for primary');
			
		//Now update the OCR for the non-primary contact
		OpportunityContactRole ocr1 = new OpportunityContactRole();
			
		ocr1.ContactId = ci.Id;
		ocr1.OpportunityId = o.Id;
		ocr1.IsPrimary = FALSE;
		ocr1.Role = 'Decision Maker';
		insert ocr1;
		System.debug('created opportunity contact role for non-primary contact');
		
		Update o;
					
	}
}

 
This was selected as the best answer