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:
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!