I have the following code where the intent is to log the details of the object only when the value of the custom label is true. This way I can control enabling logs from custom label settings. I do understand that there is also way to implement this through custom settings where we can define the data in test class. But wondering how do we cover the following code in test class if we were using custom label.

    if (Label.Enable_Log == 'True') {  //custom label
    //Initialize Log params
    logging goes in here
  • 1
    Custom Labels are not for application settings. That's specifically what Custom Settings are intended for. Why are you doing this with a label? – Mark Pond Apr 26 '18 at 23:30
  • It is just a thought process to see if this is possible. – user28452 Apr 26 '18 at 23:33
  • If for some reason you really need to test logic built around Label values, it's probably time to go to dependency injection rather than referencing the Label directly. – David Reed Apr 26 '18 at 23:39

I have seen enough incorrect usage of labels for storing application settings that I am going to document an appropriate solution that uses a Hierarchy custom setting object to control application logic.

Hierarchy Custom Setting for Log Settings

<?xml version="1.0" encoding="UTF-8"?>
<CustomObject xmlns="http://soap.sforce.com/2006/04/metadata">
        <description>When checked, logging is enabled</description>
        <label>Enable Logging</label>
    <label>Log Settings</label>

Your Class

// get the settings for the current user
LogSettings__c logSettings = LogSettings__c.getInstance();

// check the value and run if it has been enabled
if (logSettings.Enable_Log__c == true) {
    //Initialize Log params
    logging goes in here

Unit Test

static testMethod void yourTest(){ 

    // create the setting record to enable logging "org wide"
    LogSettings__c logSettings = LogSettings__c.getOrgDefaults();
    logSettings.Enable_Log__c = true;
    upsert logSettings;


    // call your class and log some things


    // assert that your logger logged what you expected

  • I'd submit that it is best of all to abstract the custom setting behind a utility class to make it resilient against changes to the underlying configuration structure. But that might be more in the realm of opinion; this is definitely best practice. – David Reed Apr 27 '18 at 0:02
  • @Mark : Thanks for detailed explanation and this worked. – user28452 Apr 27 '18 at 16:31

You should receive following error by comparing label value and Boolean.

Comparison arguments must be compatible types: String, Boolean

  • It was a mistake in my post. Updated the code. – user28452 Apr 26 '18 at 23:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.