+ Start a Discussion

How to write a test class for the following trigger

rigger countcontacts on Contact (after delete, after insert, after undelete) {
03    if(trigger.isAfter){
04         set<id> setOfAccId = new set<id>(); // create a set of contact account id
05       if(trigger.isInsert  || trigger.isUnDelete){
06            for(contact ocontact :trigger.New){   // play a for each loop at fill the set of id with account (id)
07                 setOfAccId.add(ocontact.AccountId);  
08            } 
09       }
10      if(trigger.isDelete){
11             for(contact ocontact :trigger.old){
12                setOfAccId.add(ocontact.AccountId);
13            }
14        } 
16         // create a list for update Account
17         List<Account> accountUpdate = new List<Account>();
18         List<Account> getacc = [Select Number_of_contact__c, Id, (Select Id From contacts) FromAccount WHERE ID IN :setOfAccId];
19          for(Account acc :getacc){
20             Integer ppCount = 0;
21                for(contact ocon: acc.contacts){
23                          ppCount++ ;
25                } // inner for loop close
27                if(acc.Number_of_contact__c != ppCount){
29                    acc.Number_of_contact__c = ppCount ;
30                    accountUpdate.add(acc);
31                 }
32          }// outer for loop close
34        if(accountUpdate.size() > 0){
36          update accountUpdate ;
38          }
      } // Trigger.isAfter closed
hi aman
try below code for 100% coverage
public class TestForTrigger {
    static testMethod void sampleMethod() {
       account acc = new account();
       acc.name = 'testacc';
       insert acc; 
        // give test data for all required account fields 
       contact con =  new contact();
       con.lastName = 'test'; 
       con.AccountId = acc.Id; 
       // give test data for all required contact fields 
        insert con;
        delete con;
        undelete con;
let me inform if it helps you

for test class best practice


Please follow below salesforce Best Practice for Test Classes :-

1. Test class must start with @isTest annotation if class class version is more than 25
2. Test environment support @testVisible , @testSetUp as well
3. Unit test is to test particular piece of code working properly or not .
4. Unit test method takes no argument ,commit no data to database ,send no email ,flagged with testMethod keyword .
5. To deploy to production at-least 75% code coverage is required
6. System.debug statement are not counted as a part of apex code limit.
7. Test method and test classes are not counted as a part of code limit
9. We should not focus on the  percentage of code coverage ,we should make sure that every use case should covered including positive, negative,bulk and single record .
Single Action -To verify that the the single record produces the correct an expected result .
Bulk action -Any apex record trigger ,class or extension must be invoked for 1-200 records .
Positive behavior : Test every expected behavior occurs through every expected permutation , i,e user filled out every correctly data and not go past the limit .
Negative Testcase :-Not to add future date , Not to specify negative amount.
Restricted User :-Test whether a user with restricted access used in your code .
10. Test class should be annotated with @isTest .
11 . @isTest annotation with test method  is equivalent to testMethod keyword .
12. Test method should static and no void return type .
13. Test class and method default access is private ,no matter to add access specifier .
14. classes with @isTest annotation can't be a interface or enum .
15. Test method code can't be invoked by non test request .
16. Stating with salesforce API 28.0 test method can not reside inside non test classes .
17. @Testvisible annotation to make visible private methods inside test classes.
18. Test method can not be used to test web-service call out . Please use call out mock .
19. You can't  send email from test method.
20.User, profile, organization, AsyncApexjob, Corntrigger, RecordType, ApexClass, ApexComponent ,ApexPage we can access without (seeAllData=true) .
21. SeeAllData=true will not work for API 23 version eailer .
22. Accessing static resource test records in test class e,g List<Account> accList=Test.loadData(Account,SobjectType,'ResourceName').
23. Create TestFactory class with @isTest annotation to exclude from organization code size limit .
24. @testSetup to create test records once in a method  and use in every test method in the test class .
25. We can run unit test by using Salesforce Standard UI,Force.com IDE ,Console ,API.
26. Maximum number of test classes run per 24 hour of period is  not grater of 500 or 10 multiplication of test classes of your organization.
27. As apex runs in system mode so the permission and record sharing are not taken into account . So we need to use system.runAs to enforce record sharing .
28. System.runAs will not enforce user permission or field level permission .
29. Every test to runAs count against the total number of DML issued in the process .
Would you please bulkify it?
Amit Chaudhary 8Amit Chaudhary 8
Please try below test class with below changes
1) bulkify Test
2) Assert
3) With Test.startTest and Test.StopTest.
public class countcontactsTest 
    static testMethod void testMethod1() 
		Account acc = new Account();
		acc.Name ='Test';
		// add all required field
		insert acc;
		List<Contact> lstCont = new List<Contact>();
		for(Integer i = 0 ;i<=10 i++)
			contact cont =  new contact();
			cont.FirstName ='Test';
			cont.LastName ='Test'+i;
			cont.accountid = acc.id;

			insert lstCont;
			delete lstCont;

			Account acc = [select id,Number_of_contact__c from account where id =:acc.id];
			System.assertEquals(acc.Number_of_contact__c , 0 );

Let us know if this will help you.
hi aman
here is bulkfy version with 100% code covage
public class TestForTrigger {
    static testMethod void sampleMethod() {
   //first add test dummy data     
       account acc = new account();
       acc.name = 'testacc';
       insert acc; 
   // give test data for all required account fields 
    List<Contact> lstContacts = new List<Contact>();
      // add 20 test contact in lstContacts list		
        for(Integer i=0 ;i < 20; i++){
			contact cont =  new contact();
			cont.FirstName ='Test';
			cont.LastName ='Test '+ i;
			cont.accountid = acc.id;
         // give test data for all required contact fields   
        // insert contact list
        insert lstContacts;
        // delete contact list
        delete lstContacts; 
        Account oAcc = [select id,Number_of_contact__c from account where id =:acc.id];
        System.assertEquals(oAcc.Number_of_contact__c , 0 ); 
        undelete lstContacts;
        Account oAcc2 = [select id,Number_of_contacts__c from account where id =:acc.id];
        system.debug('3' + oAcc2.Number_of_contact__c);
        System.assertEquals(oAcc2.Number_of_contact__c , 20 );

let me inform if my answer helps you