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
Palmira AngelovaPalmira Angelova 

Help writing test coverage

Hi everyone,

I'm an experienced admin, but am very new to development (just learning random bits here and there, as I don't have enough time in my job to do this the proper way.) I'm trying to deploy the code below but am not able to write a test that the Salesforce org will accept as >0%. I have tested all the functionality I need and am confident this won't break anything.

If someone could help create some very simple test coverage so I can push this to production, I'd be incredibly grateful. Thank you!

New Opportunity Trigger: 

trigger NumberofContactRoles on Opportunity (before update, after undelete) 

{
Set<Id> opportunityIds = Trigger.newMap.keySet();
List<OpportunityContactRole> contactRoles = [
        SELECT OpportunityId, IsPrimary
        FROM OpportunityContactRole
        WHERE OpportunityId IN :opportunityIds
];

Set<Id> opportunitiesWithContactIds = new Set<Id>();
Map<Id, Integer> contactRoleCount = new Map<Id, Integer>();

for (OpportunityContactRole contactRole: contactRoles) {
    if (contactRole.IsPrimary == True) {
        opportunitiesWithContactIds.add(contactRole.OpportunityId);
    }
    if (contactRoleCount.containsKey(contactRole.OpportunityId)) {
        contactRoleCount.put(contactRole.OpportunityId,
                contactRoleCount.get(contactRole.OpportunityId) + 1
        );
    } else {
        contactRoleCount.put(contactRole.OpportunityId, 1);
    }
}

for (Opportunity oppty : system.trigger.new) {
    if (contactRoleCount.containsKey(oppty.Id)) {
        oppty.Number_of_Contact_Roles_Assigned__c = contactRoleCount.get(oppty.Id);   
    } else {
        oppty.Number_of_Contact_Roles_Assigned__c = 0;
    }
}
}
Best Answer chosen by Palmira Angelova
David HalesDavid Hales
Hi Palmira,
Please tyr this one

@isTest
public class NumberofContactRoles_Test{

    public static testmethod void TestCase1()
    {
    
    Contact ConTest = new Contact();
    ConTest.FirstName = 'TEstCon';
    ConTest.LastName = 'LastName';
    
    insert ConTest;
    System.assertNotEquals(null,ConTest.Id);
    
    Opportunity Opp1 = new Opportunity();
    
    Opp1.Name = 'TestOpp';
    Opp1.StageName = 'Prospect';
    Opp1.CloseDate = System.today()+10;
    
    insert Opp1;
    System.assertNotEquals(null,Opp1.Id);
    
    OpportunityContactRole oppRole = new OpportunityContactRole();
    oppRole.OpportunityId = Opp1.Id;
    oppRole.IsPrimary = True;
    oppRole.ContactId = ConTest.Id;
    
    insert oppRole;
    System.assertNotEquals(null,OppRole.Id);
    
    Opp1.Name = 'TestOpp2';
    update Opp1;
    
    }
}

Thanks & Regards
David Hales (KSPL1021)

All Answers

PawanKumarPawanKumar
@isTest
private class OpportunityTriggerTest {

 public static testMethod void testTrigger() {
Opportunity opty = new opportunity();
// set mandatory field before insert
insert opty; // the momment this will insert, your trigger will get called.
 }
}

Please use below link for undelete
https://developer.salesforce.com/forums/?id=906F000000090JXIAY

You can learn by using below trailhead.
https://trailhead.salesforce.com/en/modules/apex_testing/units/apex_testing_triggers

Regards,
Pawan Kumar

PS: Please let me know if it helps you.
David HalesDavid Hales
Hi Palmira,
Please tyr this one

@isTest
public class NumberofContactRoles_Test{

    public static testmethod void TestCase1()
    {
    
    Contact ConTest = new Contact();
    ConTest.FirstName = 'TEstCon';
    ConTest.LastName = 'LastName';
    
    insert ConTest;
    System.assertNotEquals(null,ConTest.Id);
    
    Opportunity Opp1 = new Opportunity();
    
    Opp1.Name = 'TestOpp';
    Opp1.StageName = 'Prospect';
    Opp1.CloseDate = System.today()+10;
    
    insert Opp1;
    System.assertNotEquals(null,Opp1.Id);
    
    OpportunityContactRole oppRole = new OpportunityContactRole();
    oppRole.OpportunityId = Opp1.Id;
    oppRole.IsPrimary = True;
    oppRole.ContactId = ConTest.Id;
    
    insert oppRole;
    System.assertNotEquals(null,OppRole.Id);
    
    Opp1.Name = 'TestOpp2';
    update Opp1;
    
    }
}

Thanks & Regards
David Hales (KSPL1021)
This was selected as the best answer
Palmira AngelovaPalmira Angelova

David and Pawan, thank you for your replies! Seeing this written out for this use case is very helpful for my learning as well. 

David, thank you for the code, this is exactly what I needed. Our Salesforce currently mandates that a product be added to every oppty in order to edit it (this is done via code that I've actually erased this code and replaced with a validation rule as part of the change set I'm trying to push.) But it seems because this code is currently in production it's preventing me from running your test class. To address this, I tried writing in a product your test class based off other code I've seen. However, I'm running into the below error and can't figure out what I'm doing wrong - selecting a price book is not like creating an object like an oppty or product in my eyes, so not sure how this applies:
"System.QueryException: List has no rows for assignment to SObject 
Stack Trace: Class.NumberofContactRoles_Test.TestCase1: line 26, column 1" (this is the PriceBook2 line below)

Would you lend me your brain one more time? Thank you sincerely for your help!


@isTest
public class NumberofContactRoles_Test{

    public static testmethod void TestCase1()
    {
    
    Contact ConTest = new Contact();
    ConTest.FirstName = 'TEstCon';
    ConTest.LastName = 'LastName';
    
    insert ConTest;
    System.assertNotEquals(null,ConTest.Id);
    
    Opportunity Opp1 = new Opportunity();
    
    Opp1.Name = 'TestOpp';
    Opp1.StageName = 'Prospect';
    Opp1.CloseDate = System.today()+10;
    
    insert Opp1;
    System.assertNotEquals(null,Opp1.Id);

    Product2 pd = new Product2(Name='Additional Processor Routing2',isActive=true, Family='PR', ProductCode='Payments & Security');
    insert pd;

    PriceBook2 pb2Standard = [select Id from Pricebook2 where isStandard=true limit 1];
    Id standardPriceBookId = pb2Standard.Id;

    PricebookEntry pbe = new PricebookEntry(Pricebook2Id=standardPriceBookId, Product2Id=pd.Id, UnitPrice=99, isActive=true);
    insert pbe;
    
    OpportunityLineItem Oli1 = new OpportunityLineItem();
    Oli1.OpportunityId = opp1.Id;
    Oli1.PricebookEntryId = [select Id from PricebookEntry where isactive=true AND product2.Name='Additional Processor Routing' and Pricebook2.Isstandard=True limit 1][0].id;
    Oli1.UnitPrice = 50;
    Oli1.Quantity=10;
    insert Oli1;
    
    OpportunityContactRole oppRole = new OpportunityContactRole();
    oppRole.OpportunityId = Opp1.Id;
    oppRole.IsPrimary = True;
    oppRole.ContactId = ConTest.Id;
    
    insert oppRole;
    System.assertNotEquals(null,OppRole.Id);
    
    Opp1.Name = 'TestOpp2';
    update Opp1;
    }
}