0

The official documentation from Twilio does not specify how to mock the calls from their managed package (with namespace "TwilioSF").

How can I mock a callout like this one?

TwilioSF.TwilioApiClient api = new TwilioSF.TwilioApiClient();
api.addUrlPart('Accounts');
api.addUrlPart(ACCOUNT_SID);
api.addUrlPart('Messages.json');

api.addParam(FROM_PARAMETER, SENDER_PHONE);
api.addParam(TO_PARAMETER, recipientPhone);

api.addParam(BODY_PARAMETER, messageText);

return api.doPost(); // TwilioSF.TwilioApiClientResponse

1 Answer 1

1

When you have Twilio's package installed in your org you are able to access the accessible methods from the classes through the developer console. The methods are exposed as global, with no meaningful code in their scope, but at least you can see the method's signatures, their names and which type they are returning. If you look closely at the code base you'll see that they have a TwilioApiClientMock class with a setMock method, for example.

To mock those callouts you simply use that method instead of the standard Test.setMock method:

...
// considering that 'm' is an instance of your mocking class
// that implements the HttpCalloutMock interface:
MyTwilioHttpCalloutMock m = new MyTwilioHttpCalloutMock();
TwilioSF.TwilioApiClientMock.setMock(m);
Test.startTest();
...

To write the response for your mocks you can use the "send messages" resource in their documentation (the JSON examples). Those are quite straightforward in the sense of having the specific parameters for the errors and whatnot.

For example, if you want to test a success callout, then return 200 as the status code in your mock, and a JSON payload that contains the information you want. If the request is not successful, then return 40X or 50X, depending on what you might want to test (client error or service unavailability, respectively).

To access the various features that might be of your interest, check what the TwilioApiClientResponse does, and which methods it implements. For example, if you are unsure if the response contains an error or not, it implements a .hasErrors method that returns a Boolean, which I'm assuming is an indicator of errors in the payload processing. It also implements getHtttpStatusCode and getResponseBody methods, which might be more than enough for testing those callouts in unmanaged Apex.

You must log in to answer this question.

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