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
albonillalbonill 

Need help creatng a test for trigger

Hi,

 

I got assistance creating my trigger and now I find out that it needs to be tested in order to be uploaded to production.  The trigger is designed to auto-populate the Opportunity_Contact__c field, with the Contact that has been designated as the Renewal Owner, when a record is originally created only.  Any assistance would be greatly appreciated.

 

trigger setRenewalOwnerContact on Opportunity (before insert) {

 

 List<Opportunity > optylist = Trigger.new; 
  for ( Opportunity opty : optylist ) {
   if (opty.Opportunity_Contact__c == null) {
    for (List<Contact> contactlist : [SELECT id FROM Contact WHERE Accountid = :opty.Accountid AND Contact_Type__c = 'Renewal Owner' LIMIT 1]) { 
     for(Contact con : contactlist ) {
        opty.Opportunity_Contact__c = con.id;
     }
    }
   }
  }
  
}

 Regards,

 

Alex

Best Answer chosen by Admin (Salesforce Developers) 
ClintLeeClintLee

I updated the code above again and highlighted the changes in bold.

 

The problem could have been solved in two ways: 1) changing the trigger to an AFTER INSERT or; 2) modifying the code as I did.  Changing to an After Insert would have been easier but I just left it as a Before Insert since that's the way you had it. 

 

The issue was that the SOQL query referenced the Opportunity Id but since the records hadn't been inserted yet ( since it's a before insert trigger ) there was no Opportunity Id. 

 

Anyway, try it again.

 

~ Clint

All Answers

Richa KRicha K

Hi, Please change your code to :

 

trigger setRenewalOwnerContact on Opportunity (before insert) 
    {
     for ( Opportunity opty : Trigger.new ) 
        {
            if (opty.Opportunity_Contact__c == null) 
                    {
                    for(Contact con : [SELECT id FROM Contact WHERE Accountid = :opty.Accountid AND Contact_Type__c = 'Renewal Owner' LIMIT 1] ) 
                                 {
                                    opty.Opportunity_Contact__c = con.id;
                                 }
                    }
        }

 For test, Create a test contact with type = 'Renewal Owner' and create a test opportunity. Insert the opportunity.

ClintLeeClintLee

You might want to first re-write your trigger so that you don't have a SOQL query inside the for-loop.  Otherwise, you'll probably hit a governor limit if you every insert a bulk of Opportunities.

 

Try it this way.

 

trigger setRenewalOwnerContact on Opportunity ( before insert ) {

   Map<Id,Id> acctToContactMap = new Map<Id,Id>();

   Set<Id> acctIds                         = new Set<Id>();

  

    for( Opportunity o : Trigger.New ) {

          acctIds.add( o.AccountId );

    }

   

    for( Contact c : [ select AccountId, Id from Contact where AccountId IN :acctIds and Contact_Type__c = 'Renewal Owner'  ] ) {

           acctToContactMap.put( c.AccountId, c.Id );

     } 

 

    for( Opportunity opty : Trigger.New ) {

          if( opty.Opportunity_Contact__c == null && opty.AccountId != null ) {

              opty.Opportunity_Contact__c = acctToContactMap.get( opty.AccountId );

          }

    }

}

 

To test it.

 

public class OpportunityTriggerTest {

 

            static testmethod void testOne() { 

                       Account a = new Account( Name = 'Test Account' );

                       insert a;

 

                       Contact c = new Contact( FirstName = 'Testy', LastName = 'Testerson', Contact_Type__c = 'Renewal Owner', AccountId = a.Id );

                       insert c;

 

                       Opportunity o = new Opportunity( Name = 'Test Opp', StageName = 'Prospecting', CloseDate = System.Today(), AccountId = a.Id );

                       insert o;

 

                       o = [ select Opportunity_Contact__c from Opportunity where Id = :o.Id ];

                       System.assertEquals( c.Id, o.Opportunity_Contact__c );

            }

}

albonillalbonill

Thanks for the detailed answser.  I changed my trigger to what you suggested and I received this message when trying to save it:

 

ErrorError: Compile Error: unexpected token: 'Trigger.New' at line 7 column 124

 

Any suggestions?

ClintLeeClintLee

Put a colon in front of Trigger.New in the SOQL query.  I updated the code that I posted earlier so you'll see the change.

 

Clint

albonillalbonill

Hello billyclint,

 

I don't know how long it's going to take to me to know as much as you, but I'm sure it isn't going to be soon.  I was able to save the Trigger just fine with the updated code.

 

I ran the test and these are the results:

 

Method Name: OpportunityTriggerTest.testOne

Message: System.AssertException: Assertion Failed: Expected: 003S000000VI8qNIAT, Actual: null

Stack Trace: Class.OpportunityTriggerTest.testOne: line 28, column 1

 

I really appreciate your help.

Richa KRicha K

Hi,

 

Please change :

 

Opportunity o = new Opportunity( Name = 'Test Opp', StageName = 'Prospecting', CloseDate = System.Today(), AccountId = a.Id );

                     

 

With :

 

Opportunity o = new Opportunity( Name = 'Test Opp', Opportunity_Contact__c=c.id, StageName = 'Prospecting', CloseDate = System.Today(), AccountId = a.Id );

ClintLeeClintLee

I updated the code above again and highlighted the changes in bold.

 

The problem could have been solved in two ways: 1) changing the trigger to an AFTER INSERT or; 2) modifying the code as I did.  Changing to an After Insert would have been easier but I just left it as a Before Insert since that's the way you had it. 

 

The issue was that the SOQL query referenced the Opportunity Id but since the records hadn't been inserted yet ( since it's a before insert trigger ) there was no Opportunity Id. 

 

Anyway, try it again.

 

~ Clint

This was selected as the best answer
albonillalbonill

Clint,

 

Thanks for your assistance.  I was able to get 100% coverage using your code - two thumbs up!  I really appreciate your expertise and I hope that I acquire the Apex knowledge you have someday. 

 

 

Regards,

Alex