親子の関係(主従でない)の時に集計項目が定義できないのでApexトリガーで実装しますが、毎回同じようなコードを一から書いているのでちょっと記録しています。
trigger ContactTrigger on Contact (After insert,after update ,after delete) {
Set<Id> AccountIdSet = new Set<Id>();
if (Trigger.isDelete || Trigger.isUpdate) {
for (Contact co : Trigger.old){
AccountIdSet.Add(co.AccountId);
}
}
if (Trigger.isInsert || Trigger.isUpdate) {
for (Contact co : Trigger.new){
AccountIdSet.Add(co.AccountId);
}
}
List<Account> AccountList = [SELECT Id , (SELECT Id from Contacts) FROM Account WHERE Id =:AccountIdSet];
List<Account> updateAccountList = new List<Account>();
for (Account ac : AccountList ){
Account upAc = new Account();
upAc.Id = ac.Id;
if ( ac.Contacts.size () >0 && ac.Contacts != null){
upAc.Contacts_cnt__c = ac.Contacts.size ();
} else {
upAc.Contacts_cnt__c = 0;
}
updateAccountList.add(upAc);
}
if ( updateAccountList.size() > 0) update updateAccountList;
}
同じ機能のトリガでテストクラスが欲しいみたい。
how to write test class for this trigger?
@istest
public class RelatedContactTrigger_test {
@istest
public static void testfunc() {
test.startTest();
Account acc = New Account();
acc.Name ='test';
insert acc;
Contact con = new Contact();
con.LastName = 'No 1';
con.AccountId = acc.id;
insert con;
List<Account> accList = [select Id,Count_of_Contacts__c from Account where Id =: acc.Id];
system.assertEquals(accList[0].Count_of_Contacts__c, 1);
Contact con2 = new Contact();
con2.LastName = 'No 2';
con2.AccountId = acc.id;
insert con2;
delete con;
List<Account> accList2 = [select Id,Count_of_Contacts__c from Account where Id =: acc.Id];
system.assertEquals(accList2[0].Count_of_Contacts__c, 1);
test.stopTest();
}
}