salesforce

In This blog I Explain  how to Handle validation error message  in test class.

Sometimes we faces problem  while writing a test class for  an object on which some validation rule is active on any field .

To overcome validation error message  you just need to place your insert or update statement in try and catch block .

Here is the example  to Handle validation error message in test class:

@istest
public class Opportunity_Field_Validation_Test {

      @isTest static void TestOpportunityValidation() {
          DmlException unexpectedException;

// create test data
          List<opportunity> oppList = New list<opportunity>();
          Account acct = new Account(Name='Test Account');
          insert acct;
          Service_activator_user__c sau = new Service_activator_user__c(Name='Test1');
          insert sau;
          Opportunity opp1 = new Opportunity(Name=acct.Name + ' Opportunity',
                                             StageName='Prospecting',
                                             Contractor_New__c= sau.id,
                                             Frequency__c='1X Month',
                                             Contractor__c='CMAX1',
                                             Contractor_Pay__c=200,
                                             Avg_Service_Time__c=1,
                                             CloseDate=System.today().addMonths(1),
                                             AccountId=acct.Id);
   
          oppList.add(opp1);
          Test.startTest();

// place insert or dml within try block and handle the error in catch block 
          try{
              insert oppList;
              
          }
          catch (Exception e)
          {
              System.Assert(e.getMessage().contains('This field cannot be blank'));
          }
          Test.stopTest();
      }
    
}

 

Hits: 552

Share Post

By Himanshu Rana

My Name is Himanshu Rana, 23 Years young, born and grow up in Ghaziabad, India. A High Spirited Salesforce Admin, Developer and a Blogger. I currently work at Wakencode Technologies,

Leave a Reply

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