Use Case:

Write a trigger, when a new Account is created then create a contact related to that account.

Hint: Contact would be inserted after the account has been inserted.

// Since Contact would be created after Account is inserted,
// so here we would use “After Insert”
trigger AccountTrigger on Account (after insert) {
// Check for the context variables which would tell us that
// code should run only for “After Insert”
if(Trigger.isAfter && Trigger.isInsert) {
// Declare a List of Contacts.
List<Contact> contacts = new List<Contact>();
// Loop for each account which was inserted.
for(Account account : Trigger.new) {
// Add the contact which needs to be inserted in the list of Contacts.
Contact newContact = new Contact(LastName=account.Name+‘ Con’, AccountId=account.Id);
contacts.add(newContact);
}
// Now insert all the contacts together.
insert contacts;
}
}

Test Class: We will insert an account and then verify if the contact for that account has been created or not.

@isTest
private class AccountTriggerTest {
@isTest
static void accountTrigger_afterInsertTest() {
// Create an instance of Account
Account account = new Account(Name=‘TestAccount1’, Type=‘Prospect’);
// Perform test
Test.startTest();
insert account;
Test.stopTest();
// Fetch the account that we have inserted above.
Account insertedAccount = [Select Id, Name From Account LIMIT 1];
// Fetch the Contact for the above account and assert that a contact should be created
// also we are verifying the Account Name
List<Contact> insertedContacts = [Select Id, Account.Name From Contact];
System.assertEquals(1, insertedContacts.size(), ‘Only 1 Contact should present’);
System.assertEquals(insertedAccount.Name, insertedContacts[0].Account.Name,
Account Name does not match’);
}
}
Code Coverage: 100%
Like it ? Share : Do Nothing

This Post Has One Comment

  1. Johny Bravo

    Very nice work.

Leave a Reply