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
Rajesh Dangat 9Rajesh Dangat 9 

how to check if (test.isRunningTest() ) in test class for batch apex

Hi 
I have created one batch class that contains the following code. I want to write one logic for sandbox and one for production.   
ObjectPermissions[] objectPermissionsArray = [SELECT Id,sObjectType,parentid FROM ObjectPermissions WHERE ParentId In '...'];    
  Organization org = [select Id, IsSandbox from Organization limit 1];  
 if(org.IsSandbox || test.isRunningTest()) {    //   sandbox code
 } 
else {
 // production code }

 In test class code coverage the else block is showing in red color. and code coverage is 78%. Same happen with following condition.    
if(!objectPermissionsArray.IsEmpty()){
     code
 }else{ code } 


  Test class 
  {  test.starttest();   
       database.executeBatch(new BatchJobname());       
  test.stoptest();
  }

 
AnkaiahAnkaiah (Salesforce Developers) 
If you execute the above in sanbox then it cover olny 1st if condition and it will not go to the else part and you can't able to cover that part.
If you execute the above in production then it cover olny else condition and it will not go to the if condition part and you can't able to cover that part.

Thanks!!
 
Darshit Pathak 10Darshit Pathak 10

Your if condition will be covered in Sandbox and Production both. As you have added "Test.isRunningTest()" in OR condition. And your else part won't be covered anytime.
if you want to execute sandbox and production code everytime from test class, then instead of if... else use if.. if

if (org.IsSandbox || Test.isRunningTest()) {
//sandbox code

if (!org.IsSandbox || Test.isRunningTest()) {
//production code
}

Please mark this as best answer if it helps!!