Getting a handle on multiple HttpMockCallouts in Salesforce

Recently I've found myself in Salesforce land, having to deal with api callouts to VersionOne.  Being the second time around, I think I've got a set of classes now that really help out with this and I wanted to share my thoughts on it.

If you've attempted to test your callouts, I found either one of two things happen -- it's way too vague and/or it's way hard to test the things that are really worth testing.  You know, things that break stuff like a spelling error for a url or other silliness.  My first round of attempts looked like the examples and ended up coming out like this and felt overwhelming inadequate...

That's all well and good until you need to do multiple calls.  How would you set it up if you need to call twice or 8 times?  For my purposes, 1 call is never enough.  Sometimes it IS 8 calls, others its 2 or 3.  I also found the order to be very important as well as all the other attributes of a given request (the post data, the request url, the http status code).  As I went along and ended up with something that looks like this.

So what's all this mess?  This allows me to chain the MockCallout items, in a certain order, and to ensure the callouts are doing what they should be doing, ie, a POST vs a GET and continue passing the data along via an expected response.  Stacking a new MockCallout and provide the data necessary and pass that on to FullMultiMock to handle the order of those callouts does this for me. 

I also found it quite annoying when something went wrong inside of, say, 7 callouts, not knowing if callout 2 was the problem or 5.  This caused the assertions you see inside of FullMultiMock.  For instance, if you expect a callout to http://www.example.com/myservice/doSomething and it receives http://www.example.com/notMine/ -- the test fails like this ...

Assertion Failed: callout number : 4 actual endpoint : fake/rest-1.v1/Data/Expression expected : fake/rest-1.v1/Data/Story

Same goes for post data and the http status code.  If those don't line up, it'll fail and tell you which one it failed on.

Comments are closed