You need to sign in to do that
Don't have an account?
Ravi sastri
Test class for total number of contacts for an account
Hello Developers,
Below is my code to find total number of contacts for an account. Everything works fine here. I need to write a test class for this code. Can anyone help me with this....
Thanks in Advance!!
Below is my code to find total number of contacts for an account. Everything works fine here. I need to write a test class for this code. Can anyone help me with this....
trigger TriggerCntact on Contact (after insert, after delete) { set<ID> accSet = new Set<Id>(); if(trigger.isinsert){ for(Contact Con : Trigger.new){ accSet.add(con.AccountId); } } if(trigger.isDelete){ for(Contact Con : Trigger.old){ accSet.add(con.AccountId); } } List<Account> acclist = [SELECT Id from Account WHERE ID IN :accSet]; List<Contact> conlist = [SELECT AccountId FROM Contact WHERE AccountId IN :accSet]; list<Contact> listCon = new List<Contact>(); list<Account> listacc = new List<Account>(); map<String, Integer> conMap = new Map<String, Integer>(); for(Account acnt : acclist){ listCon.clear(); for(contact cont : conlist){ if(cont.AccountId == acnt.Id){ listcon.add(cont); ConMap.put(cont.AccountId, listCon.size()); } } } if(acclist.size()>0){ for(account a : acclist){ if(conMap.get(a.Id)==NULL){ a.Total_Contacts__c = 0; } else{ a.Total_Contacts__c = ConMap.get(a.Id); listacc.add(a); } } if(listacc.size()>0){ update Listacc; } } }
Thanks in Advance!!
Try this
@isTest
public class TriggerCntactTest{
static testMethod void TestMethodOne()
{
Account ObjAcc = new Account();
ObjAcc.name = 'Test';
insert ObjAcc;
list<contact> lstcon = new list<Contact>();
Contact objcon1 = new Contact();
objcon1.Name = 'Test1';
objcon1.Accountid = objAcc.id ;
lstcon.add(objcon1);
Contact objcon2 = new Contact();
objcon2.Name = 'Test2';
objcon2.Accountid = objAcc.id ;
lstcon.add(objcon2);
insert lstcon;
Delete objcon1;
}
}
All Answers
Try this
@isTest
public class TriggerCntactTest{
static testMethod void TestMethodOne()
{
Account ObjAcc = new Account();
ObjAcc.name = 'Test';
insert ObjAcc;
list<contact> lstcon = new list<Contact>();
Contact objcon1 = new Contact();
objcon1.Name = 'Test1';
objcon1.Accountid = objAcc.id ;
lstcon.add(objcon1);
Contact objcon2 = new Contact();
objcon2.Name = 'Test2';
objcon2.Accountid = objAcc.id ;
lstcon.add(objcon2);
insert lstcon;
Delete objcon1;
}
}