Search code examples
triggerssalesforceapex-code

trying to write a test for an apex trigger


I'm working on a trigger/test class and i can't figure out how to get the test class to work. I know that i need to update my opportunity to use the trigger but i'm not sure how to and then how to verify that my trigger is working.

Trigger:

trigger add_primary_advisor on Opportunity(before update) {
for(Opportunity o: Trigger.new){    

     if (o.IsClosed && !Trigger.oldMap.get(o.id).IsClosed) {
       OpportunityContactRole contactRole =
            [select ContactID from OpportunityContactRole where IsPrimary = true and OpportunityId = :o.id];
       if (contactRole != null) {
         o.Primary_Advisor__c=contactRole.ContactID;
       }
     }
   }    
}

Test class:

@isTest
private class primary_advisor_test {
    static testMethod void primary_advisor(){
    Opportunity opp = new Opportunity(Name='test opp', StageName='stage', Probability = 95, CloseDate=system.today());
    insert opp;


update opp; 

}

}


Solution

  • Before going into the solution for the test class I would like to point out the trigger is not builkified as you have a SOQL query inside you for loop which is not a best practice.

    I am not aware of the exact functionality of the opportunityContactRole object, I am just assuming that it is a object which will hold the contact id and the opportunityID, more or less like a junction object.

    @isTest
    private class primary_advisor_test {
      static testMethod void primary_advisor(){
      //Create a contact that will be added to the opportunityCOntactRole.
      contact con = new contact(name='testCon');// add all the required field as per your org settings
      insert Con;
      Opportunity opp = new Opportunity(Name='test opp', StageName='stage', Probability = 95, CloseDate=system.today());
      insert opp;
      //Create the opporunityContactRole.
      opportunityCOntactRole oppCOn = new new opportunityCOntactRole(OpportunityId=opp.id, contactId= con.Id, isPrimary=true);
       insert oppCon;
       //update the opportunity so that it is closed and enters the if conditon in your trigger.
       opp.stageName='Closed';
    
    
       update opp; 
    
      }
    }