function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
LakisLakis 

Test class to Update Contact record based on specific Account record type

Hey everyone,

It's my first attempt to write a test class. I have the following trigger and I'm struggling to write a test big time. Can anyone assist?

The case is pretty simple... If one of the picklist values on the Account with the specific record type 'Exhibitor'  is changed, corresponding picklists on related Contact records (Contact record type is called 'Exhibitor') must update.

***
trigger Contact_Importance_Update on Account (before update) {

    Id recTypeId = Account.sObjectType.getDescribe().getRecordTypeInfosByName().get('Exhibitor').getRecordTypeId(); //using it like this you won't have problems to deploy (and it'll save you a query)
    
    List<Account> accountsToVerify = new List<Account>();

   for(account a : trigger.new){
       if(a.RecordTypeId == recTypeId  //checks if the account has the correct RecordType
          && (a.PURE_Importance__c != trigger.oldMap.get(a.Id).PURE_Importance__c
          || a.WAA_Importance__c != trigger.oldMap.get(a.Id).WAA_Importance__c
          || a.LE_Miami_Importance__c != trigger.oldMap.get(a.Id).LE_Miami_Importance__c
          || a.PURE_Agent__c != trigger.oldMap.get(a.Id).PURE_Agent__c
          || a.LE_Miami_agent__c != trigger.oldMap.get(a.Id).LE_Miami_agent__c
          || a.WAA_agent__c != trigger.oldMap.get(a.Id).WAA_agent__c)){ //checks if the picklist is changed
           accountsToVerify.add(a);
       }
   }

   if(!accountsToVerify.isEmpty()){ //will only process if there's a need to.
      List<Contact> contactsToUpdate = [SELECT Id, AccountId, FirstName FROM Contact WHERE AccountId IN :accountsToVerify];
      for(Contact c : contactsToUpdate){
          Account a = trigger.newMap.get(c.AccountId);

          c.PURE_Importance_contact__c=a.PURE_Importance__c;
          c.We_Are_Africa_Importance_contact__c=a.WAA_Importance__c;
          c.LE_Miami_Importance_contacts__c=a.LE_Miami_Importance__c;
          c.PURE_Agent__c=a.PURE_Agent__c;
          c.LE_Miami_agent__c=a.LE_Miami_agent__c;
          c.WAA_agent__c=a.WAA_agent__c;
       }
       update contactsToUpdate;
   }


}
***

I got as far as this and I guess faaaaar away. Not sure how to relate records and how to make sure correct record type is called.

@isTest
                private class Contact_Update
                {
                     static testMethod void Contact_Importance_Update()
                  {
                                        
                    Account acc = new Account(name = 'testaccount',Street__c = 'teststreet', Country_area_code__c = 'Afghanistan (GMT +4:30; area code +93)', Region__c = 'Asia - South-Central (and India Sub-Cont.)');
                    insert acc;
                    
                    Contact con = new Contact(AccountId = acc.id,lastname = 'testcontact' , firstname ='testdata1',OwnerId = Userinfo.getUserid(), Country__c = 'Afghanistan (GMT +4:30; area code +93)', Region__c = 'Asia - South-Central (and India Sub-Cont.)');
                    insert con;
                  
                    Account a = new Account();
        
                    a.PURE_Importance__c = 'Leader';
                    a.PURE_Agent__c = 'Name1';
                    a.LE_Miami_Importance__c = 'In hand';
                    a.LE_Miami_Agent__c = 'Name2';
                    a.WAA_Importance__c = 'Suspect';
                    a.WAA_Agent__c = 'Name3';
        
                    update a;
                  
                   }
                   
      
           }
Best Answer chosen by Lakis
James LoghryJames Loghry
Looks like you are on the right track!  
  1. The RecordType setup is pretty easy to do.  You query the record type by its developername and put the Id into the record's RecordTypeId field as shown below.  
  2. Additionally, it's a best practice to surround the "test vital" code with Test.startTest and Test.stopTest calls.  By "test vital", I mean the specific piece of functionality you're testing and not the data setup portion.  
  3. You'll want to add System.assert calls to make sure the trigger / apex code is behaving as expected.  Otherwise, you may get a false sense of security that your app is working as designed.
  4. I won't show this in the example, but especially with triggers, it's always a good idea to test in hundreds of records rather than one or two records. 
@isTest
private class Contact_Update{
    static testMethod void Contact_Importance_Update(){

        //Query the record types by developername to get their Ids
        RecordType acctExhibitorRT = [Select Id From RecordType Where sObjectType = 'Account' And DeveloperName = 'Exhibitor'];

        RecordType contExhibitorRT = [Select Id From RecordType Where sObjectType = 'Contact' And DeveloperName = 'Exhibitor'];                        
                 
        Account acc = new Account(
            Name = 'testaccount'
            ,Street__c = 'teststreet'
            ,Country_area_code__c = 'Afghanistan (GMT +4:30; area code +93)',
            ,Region__c = 'Asia - South-Central (and India Sub-Cont.)'
            ,RecordTypeId = acctExhibitorRT.Id //Set this account to the exhibitor Record Type
        );
        insert acc;
                    
        Contact con = new Contact(
            AccountId = acc.id
            ,Lastname = 'testcontact'
            ,Firstname ='testdata1'
            ,OwnerId = Userinfo.getUserid()
            ,Country__c = 'Afghanistan (GMT +4:30; area code +93)'
            ,Region__c = 'Asia - South-Central (and India Sub-Cont.)'
            ,RecordTypeId = contExhibitorRT.Id //Set this contact to the exhibitor record type
        );
        insert con;

        acc.PURE_Importance__c = 'Leader';
        acc.PURE_Agent__c = 'Name1';
        acc.LE_Miami_Importance__c = 'In hand';
        acc.LE_Miami_Agent__c = 'Name2';
        acc.WAA_Importance__c = 'Suspect';
        acc.WAA_Agent__c = 'Name3';
              
        Test.startTest();
        update acc;
        Test.stopTest();

        //Requery the contact record and check to make sure it was updated.
        Contact result = 
            [Select
                PURE_Importance_Contact__c
                ,We_Are_Afria_Importance_Contact__c
                ,LE_Miami_Importance_Contacts__c
                ,PURE_Agent__c          
                ,LE_Miami_agent__c
                ,WAA_agent__c
            From
                Contact
            Where
                Id = con.Id];

        System.assertEquals(acc.PURE_Importance__c,result.PURE_Importance_Contact__c);
        System.assertEquals(acc.We_Are_Africa_Importance__c = result.WAA_Importance__c);
        ...... fill in the rest of the assertions here....
    }
}

 

All Answers

James LoghryJames Loghry
Looks like you are on the right track!  
  1. The RecordType setup is pretty easy to do.  You query the record type by its developername and put the Id into the record's RecordTypeId field as shown below.  
  2. Additionally, it's a best practice to surround the "test vital" code with Test.startTest and Test.stopTest calls.  By "test vital", I mean the specific piece of functionality you're testing and not the data setup portion.  
  3. You'll want to add System.assert calls to make sure the trigger / apex code is behaving as expected.  Otherwise, you may get a false sense of security that your app is working as designed.
  4. I won't show this in the example, but especially with triggers, it's always a good idea to test in hundreds of records rather than one or two records. 
@isTest
private class Contact_Update{
    static testMethod void Contact_Importance_Update(){

        //Query the record types by developername to get their Ids
        RecordType acctExhibitorRT = [Select Id From RecordType Where sObjectType = 'Account' And DeveloperName = 'Exhibitor'];

        RecordType contExhibitorRT = [Select Id From RecordType Where sObjectType = 'Contact' And DeveloperName = 'Exhibitor'];                        
                 
        Account acc = new Account(
            Name = 'testaccount'
            ,Street__c = 'teststreet'
            ,Country_area_code__c = 'Afghanistan (GMT +4:30; area code +93)',
            ,Region__c = 'Asia - South-Central (and India Sub-Cont.)'
            ,RecordTypeId = acctExhibitorRT.Id //Set this account to the exhibitor Record Type
        );
        insert acc;
                    
        Contact con = new Contact(
            AccountId = acc.id
            ,Lastname = 'testcontact'
            ,Firstname ='testdata1'
            ,OwnerId = Userinfo.getUserid()
            ,Country__c = 'Afghanistan (GMT +4:30; area code +93)'
            ,Region__c = 'Asia - South-Central (and India Sub-Cont.)'
            ,RecordTypeId = contExhibitorRT.Id //Set this contact to the exhibitor record type
        );
        insert con;

        acc.PURE_Importance__c = 'Leader';
        acc.PURE_Agent__c = 'Name1';
        acc.LE_Miami_Importance__c = 'In hand';
        acc.LE_Miami_Agent__c = 'Name2';
        acc.WAA_Importance__c = 'Suspect';
        acc.WAA_Agent__c = 'Name3';
              
        Test.startTest();
        update acc;
        Test.stopTest();

        //Requery the contact record and check to make sure it was updated.
        Contact result = 
            [Select
                PURE_Importance_Contact__c
                ,We_Are_Afria_Importance_Contact__c
                ,LE_Miami_Importance_Contacts__c
                ,PURE_Agent__c          
                ,LE_Miami_agent__c
                ,WAA_agent__c
            From
                Contact
            Where
                Id = con.Id];

        System.assertEquals(acc.PURE_Importance__c,result.PURE_Importance_Contact__c);
        System.assertEquals(acc.We_Are_Africa_Importance__c = result.WAA_Importance__c);
        ...... fill in the rest of the assertions here....
    }
}

 
This was selected as the best answer
James LoghryJames Loghry
Both of those are typos on my part.  

Line 53 should read:

Id = :conId];

Line 56 should read: 

System.assertEquals(acc.We_Are_Africa_Importance__c,result.WAA_Importance__c);
LakisLakis

Hi James, thank you so much for taking time and explaining this. That's excatly what I needed (I mean //explanations). 

I'm trying to test this and I'm getting the folloowing error: expecting a colon, found 'con.Id' at line 53 column 21 - I don't understand why colon is expected? 

Also, with regards to System assert equals I'm getting: Compile Error: Method does not exist or incorrect signature: System.assertEquals(String) at line 55 column 9?
LakisLakis
Thanks but now I'm getting this: Variable does not exist: conId at line 53 column 23

I think it should be: 

Id = :con.Id]; ?
James LoghryJames Loghry
Yes.
LakisLakis
Hi James,

I hope this finds you well... I have a question on the trigger above: 

Id recTypeId = Account.sObjectType.getDescribe().getRecordTypeInfosByName().get('Exhibitor').getRecordTypeId()

This method is getting "Exhibitor" account record types. How can I add additional record types i.e. "Allied Industry" or "Tourist Board"?

Many thanks in advance.

Lakis