APIs with the force.com platform are incredibly powerful. They let developers perform simple CRUD operations with the most basic code. The use of various API methods is only becoming more and more common. And yet there are scant few concrete examples of writing a test class. Searching generally turns up high-level examples and descriptions. This post is geared to correct that problem. It’s a very simple, yet concrete example of a REST API class and a related test class required for deployment. Nothing fancy, but, shockingly lacking across the salesforce development ecosystem.
Let’s set the stage
What you see below is a very simple class that leverages the Rate custom object. Rate records are incredibly basic. They hold a handful of details around the cost for a service. This includes fields like Name and Cost. The ROWSRate class below simply returns a list of the Rate items and their cost as a JSON object in about 20 lines of code. That’s it.
How do you test?
The short answer is the same as with any Apex class; a test class. You’re likely wondering “How do we provide the test data that force.com would be sending when ROWSRate is requested?” That, my dear developer friend, comes by way of the RestRequest and RestResponse objects that you’re likely already familiar with. An object of each will need to be created and you’ll proceed to fill the RestRequest object – req in my code – with your challenge data. Once your challenge RestRequest object has been filled it’s time to call ROWSRate to request data from the actual org. The data was injected into the org through utility classes in line 10 and 11, then saved as testBlob. Now you’ve all the pieces, so perform challenges between the org data (testBlob) and the data that came from API, the req RestRequest object.
Do you guys have any tricks for testing your usages of REST APIs in the force.com platform?