Sometimes we have to write code that executes differently if the Apex is being tested. For a great example, check out Scott Hemmeter's blog post on testing webservice callouts at http://sfdc.arrowpointe.com/2009/05/01/testing-http-callouts/.
Scott's example works well, and he uses a Boolean isApexTest
, running certain code if this is true or false. I used to do something similar.
The disadvantage is that one has to declare one more variable, assign a new value to it from the test code (or call a special method from the test code which, in my opinion, negatively impacts code readability), and (if you put your test code in a separate class) declare it as public. My Java professor would not like this, as he preferred to declare all variables private unless absolutely necessary. Sure, I could make a private Boolean and a getter, but now we're splitting hairs.
Salesforce has come to the rescue, though, with a test.isRunningTest()
method. Basically, you can use this interchangeably with your isApexTest
variable.
Here's a snippet of code (from Scott's blog post) with the old and new methods:
public static boolean isApexTest = false; public String main(){ // Build the http request // Invoke web service call String result = ''; if (!isApexTest){ // Make a real callout since we are not running a test } else { // A test is running result = FakeXMLReturnToSimulateResponse; } return result; }And now with the new method:
public String main(){ // Build the http request // Invoke web service call String result = ''; if (!Test.isRunningTest()){ // Make a real callout since we are not running a test } else { // A test is running result = FakeXMLReturnToSimulateResponse; } return result; }Some among you may want to switch the two so that we don't put a negative method response in the if evaluator, and that's okay too.
Venkat Polisetti says
David,
Excellent. I have set up a salesforce site in 2008 for our webinar registrations and I had to do exactly what you showed above with a temp variable that tracks if you are testing your code or running in real time.
Recently, I was making some changes to that old code and was thinking about this and I was sure, salesforce would have fixed this annoyance with a method call and exactly they did. My googling sent me to your site and glad you talked about it.
Thanks,
Venkat Polisetti