You need to sign in to do that
Don't have an account?
Jan Kopejtko 1
Test class for my trigger help
Hi, I found a great trigger that would help me with my thing - it populates my Number_of_Contacts__c field on accounts with the amount of the contacts related to the account.
But now I don't know how to write test class for this trigger. I wrote test classes for triggers before, but this one is too difficult for me at the moment. Can you write the test for me please
/* Provide summary of Number of Contacts on Account record */
trigger ContactSumTrigger on Contact (after delete, after insert, after undelete,
after update) {
Contact[] cons;
if (Trigger.isDelete)
cons = Trigger.old;
else
cons = Trigger.new;
// get list of accounts
Set<ID> acctIds = new Set<ID>();
for (Contact con : cons) {
acctIds.add(con.AccountId);
}
Map<ID, Contact> contactsForAccounts = new Map<ID, Contact>([select Id
,AccountId
from Contact
where AccountId in :acctIds]);
Map<ID, Account> acctsToUpdate = new Map<ID, Account>([select Id
,Number_of_Contacts__c
from Account
where Id in :acctIds]);
for (Account acct : acctsToUpdate.values()) {
Set<ID> conIds = new Set<ID>();
for (Contact con : contactsForAccounts.values()) {
if (con.AccountId == acct.Id)
conIds.add(con.Id);
}
if (acct.Number_of_Contacts__c != conIds.size())
acct.Number_of_Contacts__c = conIds.size();
}
update acctsToUpdate.values();
}
But now I don't know how to write test class for this trigger. I wrote test classes for triggers before, but this one is too difficult for me at the moment. Can you write the test for me please
/* Provide summary of Number of Contacts on Account record */
trigger ContactSumTrigger on Contact (after delete, after insert, after undelete,
after update) {
Contact[] cons;
if (Trigger.isDelete)
cons = Trigger.old;
else
cons = Trigger.new;
// get list of accounts
Set<ID> acctIds = new Set<ID>();
for (Contact con : cons) {
acctIds.add(con.AccountId);
}
Map<ID, Contact> contactsForAccounts = new Map<ID, Contact>([select Id
,AccountId
from Contact
where AccountId in :acctIds]);
Map<ID, Account> acctsToUpdate = new Map<ID, Account>([select Id
,Number_of_Contacts__c
from Account
where Id in :acctIds]);
for (Account acct : acctsToUpdate.values()) {
Set<ID> conIds = new Set<ID>();
for (Contact con : contactsForAccounts.values()) {
if (con.AccountId == acct.Id)
conIds.add(con.Id);
}
if (acct.Number_of_Contacts__c != conIds.size())
acct.Number_of_Contacts__c = conIds.size();
}
update acctsToUpdate.values();
}
Cheers