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
akkkakkk 

how to write a test class of the delete trigger ?

its my Trigger

// this trigger used and sum of the contact on the account object
trigger countcontacts on Contact (after insert, after delete) {
    Set<Id> aId = new Set<Id>();
    
    if(Trigger.isInsert){
        System.debug('Insert contact for trigger.new - '+Trigger.New);
        for(Contact opp : Trigger.New){
            aId.add(opp.AccountId);
        }
        List<Account> acc = [select id,sum_of_the_contact__c from Account where Id in:aId];
        List<Contact> con = [select id from contact where AccountId in :aId];
        
        for(Account a : acc){
            a.sum_of_the_contact__c=con.size();
        }
        update acc;
        System.debug('Number is '+acc);
    }
    
    if(Trigger.isDelete){
        System.debug('delete contact for trigger.old - '+Trigger.Old);
        for(Contact opp : Trigger.old){
            aId.add(opp.AccountId);
        }
        List<Account> acc = [select id,sum_of_the_contact__c from Account where Id in:aId];
        List<Contact> con = [select id from contact where AccountId in :aId];
        
        for(Account a : acc){
            a.sum_of_the_contact__c=con.size();
            
        }
        update acc;
        System.debug('Number is '+acc);
    }
    }
    *****************************************
    its my test class but only covred 58% how to 100% please slove
    
    
    @isTest
public class countcontacts_Test{
    @isTest
    static void tesMethodss()
    {
        account ac=new account(name='test');
        insert ac;
        
        contact cont=new contact(lastName='test',firstName='test', Accountid=ac.Id);
        insert cont;
      
        
    }
}
**************************************************************
SaketJoshiSaketJoshi
The test methods that you have written would cover only the if (Trigger.isInsert) block of the code. In order to cover the Trigger.isDelete block, you need to write test methods that will delete the contact record
akkkakkk
please share
Akshay_DhimanAkshay_Dhiman
Hi Aqleem,

You have to delete the contact as well as account too, to get 100% code coverage and run the condition isDeleted.Here is code which has100% code coverage of your class.  

@isTest
public class countcontacts_Test{
    @isTest
    static void tesMethodss()
    {
        account ac=new account(name='test');
        insert ac;
        
        contact cont=new contact(lastName='test',firstName='test', Accountid=ac.Id);
        insert cont;
        
        Contact con = [SELECT Id from Contact where AccountId=:ac.Id];
        delete con;
        
        Account acc =[SELECT Id,Name from Account where name = 'test'];
        delete acc;
        
        
    }
}

Mark is as solution if it helps you.

Regards,
Akshay