With the Spring '12 release, salesforce.com made some great enhancements to Apex REST services (v24):
- Apex REST automatically provides the REST request and response in your Apex REST methods via a static RestContext object. You no longer need to declare a RestRequest or RestResponse parameter in your method.
- User-defined types are now allowed as Apex REST parameter types.
- Apex REST methods are now supported in managed and unmanaged packages.
- The order of elements in the JSON or XML response data no longer has to match the Apex REST method parameter order.</ul>
My favorite is the user-defined types. My REST services can now pass back a wrapper class with error messages along with the actual data. Here's what my new REST service looks like:
So now that I have my service written and running like a champ, I just need to write my unit tests. If I was writing the unit test with the previous API (v23), I would write my unit test like:
Since v24 now includes a static RestContext object, testing is a little different as you no longer need to pass a Request and Response object to the method. I searched the Apex docs but there was no mention of writing unit tests. Pat Patterson has a good blog post for Apex REST but no mention of unit testing either.
So I tried a few routes for an hour or so to no avail. I finally IM'd Pat and begged for help. I posted the question on the Force.com Discussion Boards and Pat went to work. However, before Pat could finish his investigation and provide a solution, Kartik beat him to it (thanks!!).
So here's what the unit test looks like for a v24 Apex REST service. Notice that you pass a request and response object to the RestContext but that's it. Doesn't seem very intuitive?