Created
September 22, 2016 22:09
-
-
Save AlwaysThinkin/8b38d28b82b46603779cfc1e6292bfb4 to your computer and use it in GitHub Desktop.
Before Trigger and its unit test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Trigger ContactBeforeTrigger on Contact (before insert) { | |
for(Contact c : Trigger.new){ | |
c.Title = 'Admin'; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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