15

What is considered a best practice for writing a unit test (to maintain code coverage) on a trigger whose sole function is making a callout (Which also means it has to use a future method)? Neither futures or callouts can be tested so there really isn't anything to do.

What I've been doing is firing an add and/or update and just asserting that it added or updated correctly. Since there is also code to skip the callout if it's a test even this doesn't really test anything. Is this about the best we can hope for right now?

1
  • 1
    Nice question, getting coverage on callout is something which has troubled me in the past. Aug 11, 2012 at 9:37

2 Answers 2

14

Both future methods and callouts can be unit tested.

To test future methods simply make your call to any future method between Test.startTest(); and Test.stopTest(); statements and the future method will return when Test.stopTest(); is called. See the documentation for the Test class here: System.Test

Testing callouts is a bit trickier though. Basically 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. There's one example of this method here: http://www.iterativelogic.com/unit-test-callouts-in-apex-code-part-2/

There's also an older example of callout unit testing that uses a static variable you set in your unit test. Just replace that static variable with a call to Test.isRunningTest() and their example works fairly well as well. That example can be found here: http://sfdc.arrowpointe.com/2009/05/01/testing-http-callouts/

1
5

There's a new feature coming in the next version to make testing callouts easier: https://sites.secure.force.com/success/ideaView?id=08730000000iDaEAAU

6
  • I think I heard a rumor about public implementations of global interfaces as well. Aug 21, 2012 at 23:39
  • 1
    Yep. That's in there.
    – Rich Unger
    Aug 21, 2012 at 23:40
  • 1
    Also, relevant to testing: test fixtures. Stick a CSV in a static resource and call Test.loadData() to create your test data from it.
    – Rich Unger
    Aug 21, 2012 at 23:42
  • Does the test fixtures feature bypass triggers and work on non-DML sObjects by chance (e.g. AsyncApexJob, BusinessHours)? Aug 21, 2012 at 23:45
  • No, sorry, it works just like a normal bulk insert, except that it wires up FKs for you automatically.
    – Rich Unger
    Aug 22, 2012 at 0:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .