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
CaitlinGMCaitlinGM 

testing after delete trigger

I have a complex trigger on Opportunities that is behaving exactly as I would like, but my test coverage is only at 88%. The trigger is after insert, after update, and after delete, and it's the after delete portion of the code that the test is not affecting. Here is a shortened version of the trigger showing just the after delete case. How would I go about testing this portion? I'm getting confused since it seems to be more complex than the after insert and after update cases. I tried to just create an opportunity and the related contact and then delete the opportunity and update the contact in my test, but I must need to do something else as well. Thanks for any insight. 

 

In a nutshell, what the trigger does is:  a contact is related to an opportunity by a lookup field on opportunity. When the opportunity is deleted, if its stage is Active, it decrements a counter field on the related contact (instructor). 

 

trigger InsertUpdateDelete on Opportunity (after insert, after update, after delete) {

if(trigger.isDelete){
  {
 Map<Id,Id> instructorsToOppsMap3 = new Map<Id,Id>();
 for(Opportunity A : system.trigger.old)
 	             instructorsToOppsMap3.put(A.InstructorName__c,A.Id);
	   
List<Contact> contactsToUpdate3 = new List<Contact>();
 	        
for (Contact Instructor: [SELECT Id,Active_Count__c FROM Contact WHERE Id IN:  instructorsToOppsMap3.keySet()])
    {
	          Id oppId = instructorsToOppsMap3.get(Instructor.Id);
 	          Opportunity opp = system.trigger.oldMap.get(oppId);
 	          
	        if (opp.StageName=='Active'){
 	              Instructor.Active_Count__c=Instructor.Active_Count__c - 1;
 	  
 	               contactsToUpdate3.add(instructor);
	         }
	  if(contactsToUpdate3 != null && !contactsToUpdate3.isEmpty())
 	          Database.update(contactsToUpdate3);
 	  }
 	  } 

 

Shashikant SharmaShashikant Sharma

try this

 

@isTest
private class testDeleteTrigger
{

	private static testMethod void testmethodDeleteTrigger()
        {
        //Insert Contact 
        Contact con = new Contact();
        con.LastName = 'Test Last Name';
        con.AccountId = acc.id;
        insert con;

        Opportunity opp = new Opportunity();
        opp.StageName = 'Active';
        opp.Name='Test Opportunity';
        opp.closedate = System.today();
        opp.InstructorName__c = con.id;
        insert opp;
       test.startTest();
         delete opp;
        test.StopTest();

        }
}

 let me know if any issues in it.

CaitlinGMCaitlinGM

Hmm. Thanks. I'm at 90% now. Maybe that will have to be good enough...

Shashikant SharmaShashikant Sharma

Your welcome, 

 

please mark this as solution so that others can also benifit from it.