Wednesday, 22 February 2017

Unit Test for Salesforce Rest API



  • Any test class should be annotated with @isTest annotation.
  • Test method will have an identifier as testmethod as part of the method declaration.
  • To test Rest api RestRequest and RestResponse object to be instantiated and added in RestContext instance
  • Invoke Rest Api class to get back the response.

Example shown below:


@isTest
private class RestApiSample_Test {

    static testMethod void testGetMethod() {
        RestRequest req = new RestRequest(); 
        RestResponse res = new RestResponse(); 
        
        req.requestURI = '/services/apexrest/RestApiSample'; 
        req.addParameter('userName', 'Raghav');
        req.httpMethod = 'GET';

        RestContext.request = req;
        RestContext.response = res;

        String msg = RestApiSample.getWelcomeMessage();
        system.assertEquals(msg, 'Welcome Raghav');
    }
}

Saturday, 28 January 2017

Salesforce Apex Class as REST api Get


Salesforce REST Api as Apex Class using Get Method

Salesforce enables the programmer to expose Apex class and methods through REST architecture.

To define an apex class as REST resource @RestResource annotation is used.

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

urlMapping is used to provide url path through which the class can be accessed.

Rest api supports different methods like Get, Post

To define a method as Get, we can use @HttpGet annotation.

RestContext class contains the RestRequest and RestResponse objects.

We can get the parameter using RestContext.

Full code example is shared below: