function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Abhilash DaslalAbhilash Daslal 

How to cover Test.isRunningTest() in test class

Hi guys,
how can I cover if(Test.isRunningTest()) in test class. Can anyone give an example

Thanks,
Abhilash
NagendraNagendra (Salesforce Developers) 
Hi Abhilash,

The 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, Bacth Job etc. Returns true if the code being executed is invoked from a test class otherwise returns a false.

This method usually comes in handy, when you intend to conditionally restrict execution of certain Apex code blocks, based on whether they are being invoked from a test class or not. A practical example would be that performing web service callouts in Apex are not supported within Test Code. Hence you could use the Test.isRunningTest() to conditionally identify and route the execution of a code block that calls the Test Mock framework to simulate a mock, callout reponse.

The code block would look something like this.
if(Test.isRunningTest()){
   //Invoke mock web service response
}
else{
   //Invoke web service callout
}
Refer the following links to understand further about using Test.isRunningTest()

1. https://help.salesforce.com/articleView?id=000205831&type=1
2. https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_test.htm

As Short and Sweet .. We faced in some situation ,

1. you were using object but cannot be use in a tests, or doing some Http requests.
2. In Such case there is no option, considered using " Test.isrunningTest() "
3. This Static method allows you to discover the code was run from the test method.
           *#  return hardcoded String instead of calling http request and parsing the body
           * #  return a fixed array of objects from a method  

Example:- 
 
Boolean error = testParsesResponse(response); 
if (Test.isRunningTest()) { 
  error  = false; 
} if (error) { 
  alert('There is Some Problem Please Clean Up');
​ }
the Unit test will never get into the error condition if(error), Because it's force to True in all unit Test's...

Hope this helps.

Kindly mark this as solved if the reply was helpful so that it gets removed from the unanswered queue which results in helping others who are encountering a similar issue.

Regards,
Nagendra