Wednesday, March 05, 2014

Testing Http call out using StaticResourceCalloutMock

I was working with the Http call out stuff lately and have a chance to learn on how to execute test class on this type of class.Test class...not my favorite subject in salesforce but it is very important :).

I did some googling stuff and also bump into implementation of HttpCallout mock interface-- it was like phew! But I also bumped into other option which is StaticResourceCalloutMock and MultiStaticResourceCalloutMock which seem pretty easier.

Okay let's get started!

What is StaticResourceCalloutMock?
Built-in class used to test our callouts by specifying the response body in Static Resource.

Why?
Easy instead of implement code using HttpCalloutMock interface.We just create dump response file in Static Resource then instantiate the StaticResourceCalloutMock.

Scenario:
I have class that call webservice from other server in order to get the token.It call the webservice using Http call out.So in order to let it deployed beautifully in production , I need to get higher 75% mark in test coverage.

This is the class that using Http call out.

public class GetTokenClass {
 
 public Integer statusCode ;
 public String errorMessage;

   public String getToken()

    {
     String baseUrl='www.myDomain.com/2.0/Authentication/SalesForce';
 
       HTTPRequest r = new HTTPRequest();              
       r.setEndpoint(baseURL);
       r.setMethod('POST');
       r.setTimeout(120000);
      
        HTTP http = new HTTP();
        HTTPResponse response = http.send(r);      
        XmlStreamReader reader = response.getXmlStreamReader();
               
       String  accessToken = '';
   
        if(response.getStatusCode()!=200){
           errorMessage=response.getStatusCode() +' : '+ response.getStatus();
          
         }
        else {
         while(reader.hasNext()) { 
          if (reader.getEventType() == XmlTag.START_ELEMENT) {
             if(reader.getLocalName() == 'input'){               
                string token_id = reader.getAttributeValue(null, 'id');
  
             if(token_id == 'access_token')
                  {
                      accessToken = reader.getAttributeValue(null, 'value');
                  }
              }
          }
         reader.next();
         }
        }
         statusCode=response.getStatusCode();
        
        return accessToken;
}
}

So these are the steps that I need to do in order to use StaticResourceCalloutMock .

1) Create Static Resource that contain the response body.In my case, I need to retrieve xml file.So I will upload xml file below in Static Resource.I put the name as TokenTest.




 2)Create the test class, specify the Static Resource name that previously upload.
@isTest
public class MyTestClass {
static testMethod  void testGetToken(){
     GetTokenClass  controller = new GetTokenClass();
     StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
     mock.setStaticResource('TokenTest');
        mock.setStatusCode(200);
        mock.setHeader('Content-Type', 'text/xml');
        
        Test.startTest();
        Test.setMock(HttpCalloutMock.class, mock);
     controller.getToken();
     Test.stopTest();
 }
}


 3)Run the test classs.That's all.

 Note:If we have many call out in one class- we might want to consider MultiStaticResourceCalloutMock. 

References Testing HTTP Callouts Using Static Resources