Salesforce coding lessons for the 99%
Finally, Apex tutorials for point-and-click admins! Written by a self-taught Google engineer.
  • Beginner Tutorials
    Apotheek Eindhoven
    • Apex
    • Certifications
    • Career Info
    • Technical Architect
    • Visualforce
    • Videos
  • Apex Academy
  • Success Stories
  • About Me
  • Misc
    • Mailbag
    • Challenges
    • Links
    • Login to my Org
Follow @dvdkliuor SUBSCRIBE!

Code from #Apex4Admins Webinar 3!

May 28, 2014

Here’s the code we’re using in the final #Apex4Admins webinar!

Lists

List<Food__c> dollarMenu = [SELECT Id, Name FROM Food__c WHERE Price__c = 1];
Food__c firstItem = dollarMenu[0]; // McChicken Food__c secondItem = dollarMenu[1]; // Sausage Biscuit Food__c thirdItem = dollarMenu[2]; // McDouble Food__c fourthItem = dollarMenu[3]; // Hash Browns
List<String> buddies = new List<String>();
buddies.add('Ronald McDonald'); buddies.add('Hamburglar'); buddies.add('Mayor McCheese'); buddies.add('Officer Big Mac');

Dot Notation

// Use Case #1: Access fields
String sandwichName = dollarMenu[0].Name;

// Use Case #2: Traverse relationships
String me = dollarMenu[0].Eaten_By__r.Name;

// Use Case #3: Access methods!
dollarMenu.remove(2); // Farewell McDouble
// Every data type has methods! Food__c newItem = new Food__c();
newItem.Name = 'bbq Ranch Burger'.capitalize();
dollarMenu.add(newItem);

Bind Variables

// Use variables inside your SOQL queries!
String bestMcDonaldsItem = 'Chocolate Dipped Ice Cream Cone';
List<Food__c> bestItems = [SELECT Id, Name FROM Food__c
WHERE Name = :bestMcDonaldsItem];
// You can use Lists as Bind Variables too List<String> dietFoodNames = new List>(); dietFoodNames.add('Apple Slices'); dietFoodNames.add('Side Salad'); dietFoodNames.add('Fruit & Yogurt Parfait'); List<Food__c> bannedFoods = [SELECT Id, Calories__c FROM Food__c
WHERE Name IN :dietFoodNames];

Test Class Principle #1: Create Records from Scratch

Contact dupeContact = new Contact();
dupeContact.LastName = 'Spiderman';
dupeContact.Email = 'spiderman@gmail.com';
insert dupeContact;
Lead dupeLead = new Lead();
dupeLead.FirstName = 'Peter'; dupeLead.LastName = 'Parker'; dupeLead.Company = 'Daily Bugle';
dupeLead.Email = 'spiderman@gmail.com';
insert dupeLead;

Test Class Principle #2: Use System.assertEquals()

// Example: This obviously comes out to true
System.assertEquals(true, bestWebinarEver);
// Example: This will give you an error and fail your test class!
System.assertEquals('Tom Brady', bestActiveQuarterback);
// Query the post-trigger values and assert assumptions dupeLead = [SELECT Id, Dupe_Contact__c FROM Lead WHERE Email = :dupeLead.Email LIMIT 1];
System.assertEquals(dupeContact.Id, dupeLead.Dupe_Contact__c);

Test Class Principle #3: Test Negative Scenarios Too!

// Create a lead that SHOULDN'T have a dupe
Lead uniqueLead = new Lead();
uniqueLead.LastName = 'Xavier';
uniqueLead.Company  = 'X-Men';
uniqueLead.Email = 'theprofessor@xmen.com';
insert uniqueLead; // Assert that a dupe isn't identified on the lead uniqueLead = [SELECT Id, Dupe_Contact__c FROM Lead WHERE Email = :uniqueLead.Email LIMIT 1];
System.assertEquals(null, uniqueLead.Dupe_Contact__c);

Test Class Principle #4: Test in Bulk!

// Add 200 new Contacts to a list
List<Contact> dupeContacts = new List<Contact>();
for (Integer i = 0; i < 200; i++) { Contact c = new Contact(); c.FirstName = 'David'; c.LastName = String.valueOf(i); c.Email = 'contact' + c.LastName + '@gmail.com';
dupeContacts.add(c);
} // Insert all 200 contacts at the same time
insert dupeContacts;

Deduping Trigger

// Populate a Contact Lookup field if there's a dupe!
trigger DetectDupes on Lead (before insert, before update) {
    for (Lead l : Trigger.new) {
        if (l.Email != null) {
            String leadEmail = l.Email;
List<Contact> dupeContacts = [SELECT Id FROM Contact
WHERE Email = :l.Email];
if (dupeContacts.size() > 0) {
l.Dupe_Contact__c = dupeContacts[0].Id;
} else { l.Dupe_Contact__c = null; } } else { l.Dupe_Contact__c = null; } } }

Deduping Trigger Test Class

@isTest
public class TestDeduper {
  static testMethod void testDupes() {
    // Principle #1: Create records from scratch!
Contact dupeContact = new Contact();
dupeContact.LastName = 'Spiderman'; dupeContact.Email = 'spiderman@gmail.com'; insert dupeContact;
Lead dupeLead = new Lead();
dupeLead.FirstName = 'Peter'; dupeLead.LastName = 'Parker'; dupeLead.Company = 'Daily Bugle'; dupeLead.Email = 'spiderman@gmail.com'; insert dupeLead; // Principle #2: Use System.assertEquals() dupeLead = [SELECT Id, Dupe_Contact__c FROM Lead WHERE Email = :dupeLead.Email LIMIT 1];
System.assertEquals(dupeContact.Id, dupeLead.Dupe_Contact__c);
// Principle #3: Test things that shouldn't work! Lead uniqueLead = new Lead(); uniqueLead.LastName = 'Xavier'; uniqueLead.Company = 'X-Men';
uniqueLead.Email = 'theprofessor@xmen.com';
insert uniqueLead; uniqueLead = [SELECT Id, Dupe_Contact__c FROM Lead WHERE Email = :uniqueLead.Email LIMIT 1];
System.assertEquals(null, uniqueLead.Dupe_Contact__c);
} }
9 Comments
Kim
June 10, 2014 @ 7:21 am

Do you know when the recording of the webinar will be available?

Reply
    David Liu
    June 10, 2014 @ 6:39 pm

    I’m still waiting too!!!

    “Technical difficulties” ha ha ha. Some recording software is worse than others!

    Reply
Balaji S
May 30, 2014 @ 4:21 pm

Hi David,

Should this IF in the trigger be checking for > 1 instead of > 0. If it’s just 1, the contact has just 1 record with a matching e-mail id but is may not be a duplicate. Please advise.

if (dupeContacts.size() > 0)

Reply
    Balaji S
    May 30, 2014 @ 4:24 pm

    Also, is this required? Can we not have used the dupeLead and did another INSERT. Do we have to create new instances every time a record is created? I’m asking since this test class would not have completed execution by then?

    Also, in System.AssertEquals, how would you check for divide by zero and other different kinds of real world exceptions?

    Lead uniqueLead = new Lead()

    Reply
      David Liu
      May 31, 2014 @ 9:47 am

      In the actual webinar I re-used the dupeLead record instead of creating a new one =) They’re both the same in terms of test coverage as well!

      This post has a good example of testing exceptions!
      https://www.sfdc99.com/2013/11/02/example-write-a-test-class-for-our-deduping-trigger/

      Reply
    David Liu
    May 31, 2014 @ 9:44 am

    Every record in dupeContacts is a guaranteed dupe since it has the exact same email address! So > 0 is the best way to go! (or >= 1)

    Reply
      Phantom
      May 31, 2014 @ 10:03 am

      So, even if you find one instance of a contact record that has the same e-mail id as the Lead record, is it considered a duplicate?

      Reply
        David Liu
        June 1, 2014 @ 7:19 pm

        Yup – because the user should be updating that contact instead of the lead!

        Reply
Jose Maria Claramunt
May 28, 2014 @ 12:11 pm

Rock on Dave!

Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *


*

*

Theme: Simple Style by Fimply