To write/develop a unit-test/test class for Salesforce Apex Triggers, then in the Test Class, we have to do the DML operations based on the events used in the Apex Trigger.
Sample Trigger:
trigger ContactTrigger on Contact ( before insert, before update ) {
Set < Id > setAccountIds = new set < Id > ();
for ( Contact objContact : trigger.new ) {
if ( String.isNotBlank( objContact.AccountId ) ) {
setAccountIds.add( objContact.AccountId );
}
}
Map < Id,Account > Accountmap = new Map < Id,Account > ( [
SELECT Id, BillingCity, BillingState, BillingPostalCode, BillingStreet, BillingCountry
FROM Account WHERE Id IN: setAccountIds
] );
for ( Contact objContact : trigger.new ) {
if ( String.isNotBlank( objContact.AccountId ) ) {
objContact.MailingCity = Accountmap.get( objContact.AccountId ).BillingCity;
objContact.MailingState = Accountmap.get( objContact.AccountId ).BillingState;
objContact.MailingStreet = Accountmap.get( objContact.AccountId ).BillingStreet;
objContact.MailingCountry = Accountmap.get( objContact.AccountId ).BillingCountry;
objContact.MailingPostalCode = Accountmap.get( objContact.AccountId ).BillingPostalCode;
}
}
}
Sample Test Class:
@isTest
private class ContactTriggerTest {
static testMethod void testAddr() {
Account acc = new Account(
Name = 'InfallibleTechie',
BillingCity = 'Test',
BillingState = 'Test',
BillingPostalCode = 'Test',
BillingStreet = 'Test',
BillingCountry = 'Test'
);
insert acc;
Contact con = new Contact(
LastName = 'Test',
FirstName = 'Test',
AccountId = acc.Id
);
insert con;
con = [
SELECT Id, MailingCity, MailingState, MailingPostalCode, MailingStreet, MailingCountry
FROM Contact WHERE Id =: con.Id
];
System.assertEquals( acc.BillingCity, con.MailingCity );
System.assertEquals( acc.BillingState, con.MailingState );
System.assertEquals( acc.BillingPostalCode, con.MailingPostalCode );
System.assertEquals( acc.BillingStreet, con.MailingStreet );
System.assertEquals( acc.BillingCountry, con.MailingCountry );
}
}