stratoflow

Testing your code – Using isRuningTest() and isSandbox

Testing your code before implementation is a crucial action for every programmer, and there are several different ways of doing that, but today i want to focus on two different approaches.

At first let’s take a look on isSandbox. It’s fairly simple and straightforward. In order to use this method, you have to use SOQL to retrieve isSandbox attribute from org like in the following example:

Building a new application or extending your development team?

🚀 We're here to assist you in accelerating and scaling your business. Send us your inquiry, and we'll schedule a free estimation call.

Estimate your project
Organization org = [SELECT isSandbox FROM Organization LIMIT 1];

Having that settled, we can call: org.IsSandbox which will produce a boolean value.
On the other hand, using Test.isRunningTest() produces boolean without a need to querying anything.

When you want some code in class or trigger to be executed only in tests, for example when do you need to create new object in exchange of SOQL or SOSL request, you can use Test.isRuningTest() method. This method will return “true” if the methods will be launched from test method (method with @isTest annotation), and false if will be started from methode witch isn’t placed into test class. In exchange of code in class or trigger we should use it only in justified cases. Example:

if(Test,isRuningTest()){
// do something
}else {
//do something
}

The main reason for its limited usage, is that we won’t be able to test code in else code block and our code coverage will be affected by it. Furthermore, we should use isRunningTest method in “if else” condition only when we are making a setup for functionality, for example when we are creating object, and in test we want code to use other constructor. Good practice for simple assignment operations is to use ternary operator which won’t affect our test coverage.

Hope it helps! Good luck with your work!

Building a new application or extending your development team?

🚀 We're here to assist you in accelerating and scaling your business. Send us your inquiry, and we'll schedule a free estimation call.

Estimate your project

Testimonials

They have a very good company culture of their own, which gives them a real edge compared to other providers.

CEO

Leading UK system integrator

They're very skilled technically and are also able to see the bigger picture.

Managing Partner

Scalable SaaS for healthcare IoT built on Salesforce platform

They've been consistently able to deliver work on time and within budget.

CTO

High performance SaaS for financial insitutions

We are seriously impressed by the quality and broader picture of anything they do for us.

CEO

Gold trading platform

testowy tekst

Martyna

Senior