Bypass Validation Rules while running Apex Test Class
@isTest
private class TestClassName {
@testSetup
private static void dataSetup(){
//bypass validation rules for test class
INSERT new Validation_Rule_Settings__c(
SetupOwnerId=UserInfo.getOrganizationId(),
Disable_Validation_Rules__c = true
);
}
}

Many of you may have come across the situation where you need to bypass the Validation Rules in Salesforce while running the apex classes. Reason could be anything like,

  • Generating the business test case
  • Writing test class for one of the trigger, but other object validations are frustrating you
  • You want to skip specific validation in one of the test case

etc. and so on..

In such situations, you need a handy solution to rescue.
Here is one idea that you can use to bypass validation rules while executing the test class.

  1. Create a custom setting
    Create one custom setting of type Hierarchy. Name the custom setting as ‘Validation Rule Settings’
  2. Add new Custom field to custom setting
    Add new Checkbox field to ‘Validation Rule Settings’ custom setting. Name the field as ‘Disable Validation Rules’
    Validation Rule Custom Setting
  3. Update the validation rule formula to obey settings
    Edit the validation rule that you want to bypass test class. Make it something like follows,
    AND(
    $Setup.Validation_Rule_Settings__c.Disable_Validation_Rules__c = false,
    'YOUR_VALIDATION_CONDITION'
    )

    Salesforce Validation Rule Bypass
  4. Add new Organization default value to ‘Validation Rule Settings’ custom setting and keep Disable_Validation_Rules__c field value to FALSE.
  5. Last but not the least, in your test class data setup, add one line of code to insert custom setting value with Disable_Validation_Rules__c field set to TRUE.

This setup will ensure the your validations are intact in real business use but will be skipped when executing the test class.

Bonus Tip

This solution can also be used for bypassing the validation rule for specific Profile or users. Just create new record in Hierarchy custom setting for desired profile / user and set Disable_Validation_Rules__c field value to true.