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
Kunal Purohit 4Kunal Purohit 4 

How to write test class for given trigger?

Hello All,
I have written below trigger. Now i want to write test class for same. Kindly provide your suggestion.
trigger ContactCount on Contact (after insert, after update, after delete, after undelete) {
    
    set<id> accid=new set<id>();
     if(Trigger.isInsert|| Trigger.isUpdate|| Trigger.isUndelete){
        for(Contact con:Trigger.new){
            accid.add(con.AccountId);
        }
    }

 

    if(Trigger.isDelete|| Trigger.isUpdate){
        for(Contact Con: Trigger.old){
            accid.add(Con.AccountId);
        }
    }
    
     List<Account> aclist=[SELECT Id,Open_Contact_Count__c,(SELECT Id FROM Contacts WHERE Status__c= 'Open') FROM Account WHERE Id IN: accid];
    for(Account acc: aclist){
      
       acc.Open_Contact_Count__c= acc.Contacts.size();
    }
    update aclist;
}

 
Best Answer chosen by Kunal Purohit 4
ANUTEJANUTEJ (Salesforce Developers) 
Hi Kunal,

You can try the below and modify it accordingly as it is a sample snippet.
 
@isTest
 Public Class ContactCountTest{

 Static testMethod void CountTest(){

 Account a = new Account();

 a.Name='Test Account';

 a.phone='8686864286';

 a.Rating='Hot';

 insert a;
Contact con= new Contact();
con.LastName='TestCon';
con.AccountId= a.id;
insert con;
Account atest= [SELECT Id,Open_Contact_Count__c,(SELECT Id FROM Contacts WHERE Status__c= 'Open') FROM Account WHERE Id= :a.id];
 assertEquals(1, acc.contacts.size(), 'Check the Test Class');

 }

 }
Also, I would suggest you to check implementation on https://developer.salesforce.com/forums/?id=906F0000000AcdaIAC

Let me know if it helps you and close your query by marking it as solved so that it can help others in the future.  

Thanks.