I have a requirement, where i need to populate all the related contacts in Account Object Detail Page with comma seperated. For Example : If I have Account1 and Contact1 and Contact2 are related to Account1. Then, in account object detail page, i have a text box named "Related Contacts" which will display Contact1, Contact2.
Below is the trigger for that --
trigger totalContacts on Contact (after insert,after update) {
Set<ID> setAccountIDs = new Set<ID>();
for(Contact c : Trigger.new){
setAccountIDs.add(c.AccountId);
}
List<Account> accounts = [Select ID, Name,(Select Name From Contacts) From Account WHERE ID IN :setAccountIDs];
for(Account a : accounts){
String contactName = '';
for(Contact c : a.Contacts){
contactName +=c.Name+ ' ,';
}
a.Associated_Contacts__c =contactName;
}
update accounts;
}
I wrote the below test class and it covers only 60%, please guide me to cover 100% of the code
@isTest
public class testtotalContacts{
static testMethod void insertnewContact(){
Account accountToCreate = new Account();
accountToCreate.Name = 'Test Account';
accountToCreate.AW_Expiration_date__c = System.today();
insert accountToCreate;
Contact contactToCreate1 = new Contact();
contactToCreate1.FirstName = 'Test 1';
contactToCreate1.LastName = 'Trigger test class 1';
contactToCreate1.Email = 'krishnakumar1@gmail.com';
contactToCreate1.Account = accountToCreate;
insert contactToCreate1;
Contact contactToCreate2 = new Contact();
contactToCreate2.FirstName = 'Test 2';
contactToCreate2.LastName = 'Trigger test class 2';
contactToCreate2.Email = 'krishnakumar@gmail.com 2';
contactToCreate2.Account = accountToCreate;
insert contactToCreate2;
}
}