Usage of Test.isRunningTest()

Hima Chirra
1 min readMay 10, 2021

Test.isRunningTest() method is used to identify, if the piece of code being executed is invoked from a Test class execution or from other artefacts such as a Trigger, Batch Job etc. Returns true if the code being executed is invoked from a test class otherwise returns a false.

There are some scenarios, where we couldn’t test some code blocks, eg. an if condition with dates. In such cases, if you think there is no other option, consider using Test.isRunningTest(). This static method allows you to discover whether the code was run from test method. Therefore, for example you might:

if (reportDate.daysBetween(firstDayOfMonth) == 0 || Test.isRunningTest()){
//reportdate is start of Month
AddNewFTPRecords();
//fetch new record(with report date YESTERDAY) for update
DayBeforeDate = reportDate;
}

Can be used in the SOQL with a ternary operator as below:

[select Id, name from Event__c where Start_Date__c >= TODAY (Test.isRunningTest()?’ LIMIT 200' LIMIT 200':’’)]

Usage scenarios

  1. To ensure the trigger doesn’t execute the batch if Test.IsRunningTest() is true, and then test the batch class with it’s own test method.
  2. Testing callouts — in your callout code you check to see if you’re executing within a unit test context by checking Test.isRunningTest() and instead of getting your callout response from an HttpResponse.send() request, you return a pre-built test string instead.

--

--