0

hope you're all doing well and still able to chug along during the pandemic.

Today, I'm trying to put in place some checks for sandbox so that certain classes will not run in production.

TLDR:

How do we get coverage for these scenarios to account for both successful scenario of a sandbox being true, and the failure of the sandbox being false; this is not for the SandboxPostCopy interface. This is just for a standard class.

The Problem

I have a a Utility Class that uses a Boolean Method to return the Organizations property isSandbox.

Here is the method:

public static Boolean isSandbox(){
    Organization org = [SELECT Id, isSandbox FROM Organization LIMIT 1];
        if (org.IsSandbox == true || Test.isRunningTest()) {
        return true;
    } else {
        return false;
    }
}

Where I'm trying to cover my code:

I have batch class that I am calling that here:

if (Utility.isSandbox() == true) {
            System.Debug('LEAD BATCH: running');
        } else {
            //Trying to get coverage here: 
            System.assert(false, 'You can only run this class from Sandbox');

        }

Possible Solution

The best possible solution seems to be accepting that it will fail one test in either prod and not in sbx, or in sbx and not in prod.

If I write the method logic this way:

  • Passes in sbx, and will pass in prod. But just accept that I won't have coverage for the false version of the condition.
org.isSandbox == true || Test.isRunningTest() == true {
     return true; 
}


3

You just need to allow a way to override the value:

@TestVisible static Boolean s_isSandbox = false;
static {
  s_isSandbox = [SELECT Id, isSandbox FROM Organization].isSandbox;
}
public Boolean isSandbox() {
  return s_isSandbox;
}

In your unit test, you can set the variable directly:

Utility.s_sandbox = true; // or false //

Which allows you to specify if you want to test as if it were production or not.

3
  • Am I correct though in understanding that, no matter how I write this, some section of the code is not going to be covered?
    – thinker
    Aug 7 '20 at 20:50
  • 3
    @thinker when you can control the value that your utility method returns, you gain the ability to write tests for both. Like with any other if/else, you'll want more than one test method if you want to cover both branches.
    – Derek F
    Aug 7 '20 at 20:53
  • Yup, just got it to work. Working through the system assert now.
    – thinker
    Aug 7 '20 at 21:00

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.