Testing an HTTP Callout in Salesforce

Introduction

This tutorial assumes that you already know what a Callout is, and are familiarized with terms like: endpoint, Restful services, SOAP and http requests operations (get, post, put and delete). In conclusion, we are going to show you how to make an http request with Salesforce to consume a web service, and how to test it.

Making a Callout

The “url” parameter is the endpoint that we want to hit to consume the web service and the “method” is the operation that we want to execute: “GET”, “DELETE”, “POST” or “PUT”.

So, we could call this method like this:

The response will contain a JSON that we need to parse in order to get the required data.

What about testing?

Basically, what we need to do is to construct a fake response (maybe JSON) and when the test method runs, we are going to get that response from the method we are testing or, maybe, some data that we are expecting in our test method. To explain this, let’s keep things simple and say that the method that we need to test retrieves the http response (JSON in this case).

So, how to create a fake response for testing purposes?

Just make a class that implements HttpCalloutMock:

As you can see the class has 2 constructors, one of them takes an HttpResponse so, what we can do in our test method is to create an instance of this class (FacebokRequestMock, for example, it can be whatever). Then, when the test method gets the response, it will be what we send by parameters to the FacebookRequestMock constructor. Let’s see:

Take a look at lines: 12-19, we are creating the fake JSON response and with Test.setMock we are setting that fake response to our Mock class. In this way, when the method that we need to test is executed, it’s going to retrieve that fake response.

Looks like we have all we need to implement and test an HTTP Callout in Salesforce. Let’s do it! Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *