[SalesForce] Hierarchy Custom Setting Test Class Issue

I'm using a Hierarchy Custom Setting field in a validation rule but want my trigger to be able to override the validation rule whenever it runs. I have modified my trigger/helper class to set my custom setting value to False at the beginning of the trigger and set it back to True after the trigger has ran.

My only issue is that my test classes fail with the following message: "MISSING_ARGUMENT, Id not specified in an update call: []"

If I indicate (seeAllData=True) in my test class, I can get my testMethod to pass but Zendesk has a managed package with an error in their test classes so my testClass fails.

Is there a way I can get my test class to pass without using the SeeAllData = true parameter?

Here is the snippet from my code

//Turn Custom Setting that enforces validation rule off for this trigger
    ValidationRuleExceptions__c vre = ValidationRuleExceptions__c.getInstance(UserInfo.getOrganizationId());
    vre.Enforce_Account_Validation_Rules__c = false;
    update vre;

Turning the Setting Off:

//Turns Custom setting back on
        vre.Enforce_Account_Validation_Rules__c = true;
        update vre;

I'm building an instance of the Custom Setting in my test class as well

user usr = [SELECT Id FROM User WHERE Profile.Name = 'System Administrator' AND isActive = True Limit 1];

ValidationRuleExceptions__c vre = new ValidationRuleExceptions__c(SetupOwnerId = usr.Id, Name = 'test', Enforce_Account_Validation_Rules__c = false);
        insert vre;

Best Answer

You shouldn't assume your custom settings exist; you should be able to use your code either way. Here's how I'd approach this:

ValidationRuleExceptions__c vre = ValidationRuleExceptions__c.getInstance(UserInfo.getOrganizationId());
vre.Enforce_Account_Validation_Rules__c = false;
upsert vre;

// Later...
vre.Enforce_Account_Validation_Rules__c = true;
upsert vre;

While technically you know it exists by the second point, there's really no harm in using upsert-- that's what it's designed to do, perform an insert or update as needed.

Related Topic