mathlearner
mathlearner

Reputation: 7639

Testing a Rest Web Service in salesforce.com

I am developing a Rest Web service in salesforce.com platform. I wrote it and it is working properly and giving accurate responses when I call it. The problem is how to test it

@RestResource(urlMapping='/feedpost/*')

    global class Feedpost9
    {
      @HttpPut
      global static User updateCase() {
         RestRequest req=RestContext.request;
         User user=[SELECT id from User where email=:req.headers.get('email') LIMIT 1];
         return user;          
    }

}

Now my task is to test this REST web service method updateCase. For testing a POST request method I have to set the parameters in method call but in case of PUT method - how do I set RestContext.request in the test class?

Upvotes: 4

Views: 8873

Answers (1)

slashingweapon
slashingweapon

Reputation: 11307

There are two issues you must contend with in your unit tests:

  • The need for a valid RestRequest
  • The lack of data in a test environment

Here is basic technique to setting up the request object your method wants

global class Feedpost9 {

    // your methods here...

    static testMethod void testRest() {
        // set up the request object
        System.RestContext.request = new RestRequest();
        RestContext.request.requestURI = '/feedpost/whatever';
        RestContext.request.addHeader('email', '[email protected]');
        // Invoke the method directly
        Feedpost9.updateCase();
    }
}

The other problem you're likely to have is that in Salesforce v24 and above unit-tests, by default, do not have access to your data. That's because unit tests run in a kind of sandbox that have none of your data, but do contain your metadata (RecordTypes, etc). So, there are two techniques for getting data to your tests:

  1. Use the @isTest(SeeAllData=true) annotation on your method. This will give the test method access to your data.
  2. Have your test method build/insert the test data, then run your tests against that data. When the testing ends, your test data will miraculously disappear from your database.

I prefer to use the later method, but sometimes I cheat...

Upvotes: 5

Related Questions