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
Cris9931Cris9931 

test class - trigger - addError method

Hello, I wrote a trigger to check if the url = 'https://sig-cb--Full.cs88.my.salesforce.com' and the profile of the current user is a specific profile (SIG-FSM-Super User) and if so the trigger shows an error message and also an image which I included in the addError function, it looks like this:

trigger ContactCreationForServiceMaxUsers on Contact (Before insert) {
   
       String baseURL = String.valueof(URL.getSalesforceBaseUrl());
      
       system.debug('<<baseURL>>' + baseURL);
       Boolean isBaseURL = baseURL.contains('https://sig-cb--Full.cs88.my.salesforce.com');
       System.debug(' >> String.valueof(URL.getSalesforceBaseUrl()) >>'+baseURL ); 
       User currentUser = [SELECT Id, Profile.Name FROM USER WHERE Id =:UserInfo.getUserId()]; 
      
       Contact c = new Contact(); 
      
       System.debug(' >> isBaseURL >>'+isBaseURL ); 
       System.debug(' >> currentUser.Profile.Name>>'+currentUser.Profile.Name ); 
   
     for(Contact c : Trigger.New){ 
          if(isBaseURL == TRUE  && currentUser.Profile.Name == 'SIG-FSM-Super User'){
           c.addError(' <p style="color:red; font-size: 20px;">Service contact creation is only allowed from “Account” tab using the blue button “Create Contact” after selecting a account”</p><img id="theImage" src="https://sig-cb--full--c.cs88.content.force.com/servlet/servlet.FileDownload?file=0159E0000002tNp" width="850px" height="100px" alt="Description of image here"/> ', false); 
          } 
     } 
}


Can anyone help me with how to build the test class for the trigger? At least theoretical.

1. First I need to create a contact
2. I need to create a user with a profile = 'super-user'
3. somehow i need to check the addError function..

Something like this...

Best Answer chosen by Cris9931
Maharajan CMaharajan C
Hi Sarah,

Please use the below test class:
 
@isTest
public class ContactCreationForServiceMaxUsersTest {
    
    Static testmethod void ServiceMaxUserstest(){
        Profile p = [SELECT Id FROM Profile WHERE Name='SIG-FSM-Super User'];
        User UserObj= new User(Alias = 'Test', Email='SIGFSMSuper@testorg.com',
                               EmailEncodingKey='UTF-8', LastName='SIGFSMSuper', LanguageLocaleKey='en_US',
                               LocaleSidKey='en_US', ProfileId = p.Id,
                               TimeZoneSidKey='America/Los_Angeles', UserName='SIGFSMSuper@testorg.com');
        insert UserObj;
		System.runAs(UserObj) {
        // Add the mandatory fields to create the contact record in below line.
        Contact c = new Contact(LastName ='Test Contact',Email='SIGFSMSuper@testemails.com');
        Database.SaveResult result = Database.insert(c, false);
		}
        
    }
}



Thanks,
Maharajan.C

All Answers

Maharajan CMaharajan C
Hi Sarah,

Please use the below test class:
 
@isTest
public class ContactCreationForServiceMaxUsersTest {
    
    Static testmethod void ServiceMaxUserstest(){
        Profile p = [SELECT Id FROM Profile WHERE Name='SIG-FSM-Super User'];
        User UserObj= new User(Alias = 'Test', Email='SIGFSMSuper@testorg.com',
                               EmailEncodingKey='UTF-8', LastName='SIGFSMSuper', LanguageLocaleKey='en_US',
                               LocaleSidKey='en_US', ProfileId = p.Id,
                               TimeZoneSidKey='America/Los_Angeles', UserName='SIGFSMSuper@testorg.com');
        insert UserObj;
		System.runAs(UserObj) {
        // Add the mandatory fields to create the contact record in below line.
        Contact c = new Contact(LastName ='Test Contact',Email='SIGFSMSuper@testemails.com');
        Database.SaveResult result = Database.insert(c, false);
		}
        
    }
}



Thanks,
Maharajan.C
This was selected as the best answer
Cris9931Cris9931

Hi Maharajan,

It works :). Thank you so much!

However I have a few questions... please answer if you have time.

1. When you mentioned Sytem.runAs(UserObj) - means you runned the system as that specific user? That is the purpose of this function?

2. Database.Save Result can be used instead of AssertEquals? In the past when I tried to write test classes I always used AssertEquals.

 

Thanks

Cris9931Cris9931

Also, can you please describe it in simple terms what this line does:
Database.SaveResult result = Database.insert(c, false);  
I would appreciate a lot.

Why did you use this method? I removed it and I added only insert c and the method failed with the error from the trigger..

Danish HodaDanish Hoda
Hi Sarah,
Starting with your first question:
1. System.runAs() helps us to create user and other objects in the same transaction, else we would come across MIXED-DML Error.
2. Database.saveResult() method is sued form DML operations, and has nothing to do with the assert statements.
3. Database.SaveResult result = Database.insert(c, false); 
--> the syntax is Database.SaveResult result = Database.insert(sObject object, Boolean allOrNone);  
Maharajan CMaharajan C

1. Yes Sytem.runAs(UserObj)  is used to run the test method in specific user context otherwise it will run in System Context.

2. Instead of normal dml statement you can use the Database.insert(c, false) method otherwise you have to use the try/catch in test class And here we are using the false in database.insert statement so if any error was thrown while creating/update the contact it will not throw any runtime error in UI/current transaction but the error will be saved in Database.SaveResult. So the test class will not face any failure while running but in the backend the record result will be captured so it will cover the adderror function in trigger.

3. You can also use the normal try/catch for this Adderror function.

Cover the adderror in test class using Database class:
http://www.infallibletechie.com/2015/10/how-to-cover-adderror-in-trigger-in.html

Cover the adderror in test class using using try/catch:
https://prosenjit-sarkar-sfdc.blogspot.com/2016/10/testing-adderror-method-in-apex-test.html
http://www.nisarkhan.net/?p=469


Thanks,
Maharajan.C