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
kanchan tyagi 2kanchan tyagi 2 

test class of count no of conatct trigger

trigger contactCounttriger on Contact (After insert, After Delete, After Undelete,after update) { Set<id> setAccountId=new Set<id>(); if(Trigger.isInsert || Trigger.isUndelete || Trigger.isUpdate){ for(Contact con:Trigger.New){ setAccountId.add(con.AccountId); } } if(Trigger.IsDelete){ for(Contact con:Trigger.old){ setAccountId.add(con.AccountId); } } List<Account> listAcc=[select id,no_of_contacts__c,(Select id from Contacts)from Account where id in:setAccountId]; for(Account acc:listAcc){ acc.no_of_contacts__c=acc.contacts.size(); } update listAcc; }
Dhanya NDhanya N
Hi Kanchan,

Please check below test class
@isTest
private class contactCount_Test {
    
    @isTest static void test_contactCount() {
    
        Account objAccount = new Account(Name = 'Test');
        insert objAccount;
        
        Account objAccount1 = new Account(Name = 'Test 1');
        insert objAccount1;
        
        Test.startTest();
        Contact objContact = new Contact(LastName = 'Test Contact', AccountId = objAccount.Id);
        insert objContact;
        
        Contact objContact1 = new Contact(LastName = 'Test Contact 1', AccountId = objAccount.Id);
        insert objContact1;
        
        System.assertEquals(2, [Select Number_of_Contacts__c From Account Where Id =: objAccount.Id].Number_of_Contacts__c );
        
        objContact1.AccountId = objAccount1.Id;
        update objContact1;
        
        System.assertEquals(1, [Select Number_of_Contacts__c From Account Where Id =: objAccount1.Id].Number_of_Contacts__c );
        
        delete objContact1;
        
        System.assertEquals(0, [Select Number_of_Contacts__c From Account Where Id =: objAccount1.Id].Number_of_Contacts__c );
        Test.stopTest();    
    }   
}

Thanks,
Dhanya
 
anuj huriaanuj huria
Hi kanchan,refer this code
 
@isTest
public class nocTest{
   
 public static testmethod void count()
 {
     list<account> acc=new list<account>();
     acc.add(new account(Name='anuj'));
     acc.add(new account(Name='kanchan'));
     Insert acc;
    list<Contact> con=new list<Contact>();
     con.add(new Contact(lastName='anuj', accountid=acc[0].id));
     con.add(new Contact(lastName='kanchan', accountid=acc[0].id));
     insert con;
     
   
     update con;
 delete con[1];

 }
 }

Thanks..
mark it solved so that other can take benifit from this