Let’s take Account and Contact object.
Trigger
trigger AccountTrigger on Account (after insert) {
if (Trigger.isInsert && Trigger.isAfter) {
AccountTriggerHandler.createContacts(Trigger.new);
}
}
Apex Class
public class AccountTriggerHandler {
public static void createContacts(List newAccounts) {
List contactsToCreate = new List();
for (Account acc : newAccounts) {
Contact newContact = new Contact(
FirstName = 'First Name',
LastName = 'Last Name',
AccountId = acc.Id
);
contactsToCreate.add(newContact);
}
if (!contactsToCreate.isEmpty()) {
insert contactsToCreate;
}
}
}
Apex Test Class
@isTest
public class AccountTriggerHandlerTest {
@isTest
static void testCreateContactAfterAccountInsert() {
// Test scenario where a single Account is inserted
System.Test.startTest();
Account acc = new Account(Name = 'Test Account');
insert acc;
System.Test.stopTest();
Contact createdContact = [SELECT Id, FirstName, LastName, AccountId FROM Contact WHERE AccountId = :acc.Id LIMIT 1];
// Verify that a Contact was created and is associated with the Account
System.assertNotEquals(null, createdContact, 'Contact should be created');
System.assertEquals('First Name', createdContact.FirstName, 'First Name should be default');
System.assertEquals('Last Name', createdContact.LastName, 'Last Name should be default');
System.assertEquals(acc.Id, createdContact.AccountId, 'Contact should be related to the Account');
}
@isTest
static void testCreateContactsForMultipleAccounts() {
// Test scenario where multiple Accounts are inserted
System.Test.startTest();
List accounts = new List();
for (Integer i = 0; i < 3; i++) {
accounts.add(new Account(Name = 'Test Account ' + i));
}
insert accounts;
System.Test.stopTest();
List createdContacts = [SELECT Id, FirstName, LastName, AccountId FROM Contact WHERE AccountId IN :accounts];
// Verify that a Contact was created for each Account
System.assertEquals(3, createdContacts.size(), 'There should be 3 Contacts created');
for (Account acc : accounts) {
Boolean contactExists = false;
for (Contact con : createdContacts) {
if (con.AccountId == acc.Id) {
contactExists = true;
break;
}
}
System.assertEquals(true, contactExists, 'A Contact should be created for each Account');
}
}
}