Let’s take Account and Contact object.
Trigger
trigger AccountTrigger on Account (after delete) {
if(trigger.isAfter && trigger.isDelete) {
AccountTriggerHandler.deleteRelatedContacts(trigger.old);
}
}
Apex Class
public class AccountTriggerHandler {
public static void deleteRelatedContacts(List<account> oldAccounts) {
// Collect all deleted accouts Id
Set<id> accIds = New Set<id>();
for(Account acc: oldAccounts){
accIds.add(acc.Id);
}
if(!accIds.isEmpty()) {
// Retrieve all related contact
List<contact> relatedContacts = [SELECT Id FROM Contact WHERE AccountId IN: accIds];
if(!relatedContacts.isEmpty()){
Delete relatedContacts;
}
}
}
}
Apex Test Class
@isTest
private class PracticeAccountTest {
@isTest
private static void testDeleteRelatedContacts() {
Account testAccount1 = new Account(Name = 'Test Account 1');
insert testAccount1;
Contact testContact1 = new Contact(FirstName = 'John', LastName = 'Doe', AccountId = testAccount1.Id);
insert testContact1;
Account testAccount2 = new Account(Name = 'Test Account 2');
insert testAccount2;
Contact testContact2 = new Contact(FirstName = 'Jane', LastName = 'Smith', AccountId = testAccount2.Id);
insert testContact2;
List<account> accountsToDeleteContacts = new List<account>{testAccount1, testAccount2};
List<contact> contactList = new List<contact>{testContact1, testContact2};
System.Test.startTest();
PracticeAccount.deleteRelatedContacts(accountsToDeleteContacts);
System.Test.stopTest();
List<contact> remainingContacts = [SELECT Id FROM Contact WHERE Id IN :contactList];
System.assertEquals(0, remainingContacts.size(), 'Related Contacts should be deleted');
}
}