Home > OS >  What happens when you call a test using HttpCalloutMock?
What happens when you call a test using HttpCalloutMock?

Time:12-03

This is not a code/case specific question.

I am new to Apex, and I'm trying to test methods that do Callouts to external APIs. I understand that in order to test this method, I have to create a class that implements HttpCalloutMock and use it in my test.

However, I want to know: in the Test, when I call the actual method I'm testing, does a call go out to the API behind the scenes? Or is the data I'm putting in the mock the only data that gets passed around?

(I'm asking because, if the latter, wouldn't that mean these tests are extremely counterproductive and unnecessary?)

CodePudding user response:

The dummy data you provided in the mock class will be dutifully returned. And yes, it's annoying, double work.

But how else could it be done? Really calling an external API might have bad consequences (sending "My Awesome Test Order!!!1one!eleven" to production fulfilment system would be a disaster, especially if you do it few times because deployment kept failing). And when such API would be down and you really, really need to deploy something to production - you shouldn't be a hostage of 3rd party server, even test one.

Instead of grumbling try to embrace it. Yes, it's rubbish. But this is your opportunity to test how your code handles different outputs. How it reacts when the API response is "HTTP 500 Internal Server Error", HTML instead of JSON or even there's no response, just timeout. The more solid you make it, the more confident you'll be.

Is it really that hard? Capture couple real messages & errors, remove sensitive data, implement some switch statement "if account number = 123 return this else return that" and you're done.

And yes, it essentially means implementing 3rd party's logic yourself. But well, with test-driven development you ideally would start with a dummy representation of their service anyway, something that's close enough to the API "contract" you have. And as a bonus - you get to shout at them when something suddenly breaks and you can prove it wasn't a change on your end.

In the end it's not too different from splitting work with another SF developer. "OK, I'll do the UI bit, you do the apex bit, here's the data interface we promise to use, see you in 1 week's time". How far can you trust the guy, eh? ;)

CodePudding user response:

If you go through this document you will get your answer

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_testing_httpcalloutmock.htm
Rajat Jaiswal

  • Related