Skip to content

Instantly share code, notes, and snippets.

@AlwaysThinkin
Created September 22, 2016 22:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save AlwaysThinkin/8b38d28b82b46603779cfc1e6292bfb4 to your computer and use it in GitHub Desktop.
Save AlwaysThinkin/8b38d28b82b46603779cfc1e6292bfb4 to your computer and use it in GitHub Desktop.
Before Trigger and its unit test
Trigger ContactBeforeTrigger on Contact (before insert) {
for(Contact c : Trigger.new){
c.Title = 'Admin';
}
}
@isTest
public class ContactBeforeTriggerTest {
public static testMethod void testOne(){
//Must create a test Account for the test Contact!
Account a = new Account(Name = 'Test Account');
insert a;
//Now create your test Contact
Contact c = new Contact(LastName = 'name', AccountId = a.Id);
insert c;
//Query to retrieve the Title field value for your Contact
c = [Select Title from Contact where Id = :c.Id];
//Assert that what you expect is what is actually the field value
System.assertEquals('Admin', c.Title);
}
public static testMethod void testMany(){
//Must create a test Account for the test Contacts!
Account a = new Account(Name = 'Test Account');
insert a;
//Use a for-loop to populate a List of test Contacts
List<Contact> testContacts = new List<Contact>();
for(Integer i = 0; i < 2 ; i++){
Contact c = new Contact(LastName = 'name' + i,//Use i to make each name unique
AccountId = a.Id);
testContacts.add(c);
}
insert testContacts;
//Bulk Tests also require bulk assert tests
for(Contact c : [Select Title from Contact]){
System.assertEquals('Admin', c.Title);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment