+ Start a Discussion
Baz DensonBaz Denson 

improve code coverage for @HTTP Post

My test class only has 48% coverage, can you suggest ways to improve this?

Class
 
@RestResource(urlMapping='/gocardless/*')
global with sharing class GoCardlessEndpoints {

    
  /*  
   HttpPost method is used to capture a HttpPost request has been sent to our rest apex class.  
   Used to retrieve data coming in the request body and performing corressponding actions  
  */  
  @HttpPost  
   global static String doPost() {  
     /*  
       RestContext Class - Allows us to access the RestRequest and RestResponse objects in your Apex REST methods.   
       RestRequest class - Allows us to pass request data into our Apex RESTful Web service method.  
       RestResponse class - Allows us to pass or send back response data from our Apex RESTful web service method  
     */  
     //Returns the RestRequest object for our Apex REST method.  
     RestRequest request = RestContext.request;  
     //Returns the RestResponse for our Apex REST method.  
     RestResponse response = RestContext.response;  
     //Access the request body with input data coming in the JSON format  
     String jSONRequestBody=request.requestBody.toString().trim();  
     //Deserializes the input JSON string into an GoCardless_Event__c object  

      ResponseResult e = (ResponseResult)JSON.deserialize(jSONRequestBody, ResponseResult.class);
      
       for(integer i=0; i< e.events.size(); i++) {
     
           GoCardless_Event__c gcevent = new goCardless_Event__c();
           gcevent.name = e.events[i].Id;
           gcevent.created_at__c = e.events[i].created_at;
           gcevent.resource_type__c = e.events[i].resource_type;
           gcevent.action__c = e.events[i].action;
           if (e.events[i].resource_type == 'mandates') gcevent.Link__c = e.events[i].links.mandate;
           if (e.events[i].resource_type == 'payments') gcevent.Link__c = e.events[i].links.payment;
           
           gcevent.Customer_Number__c = getCustomerNo(gcevent.Link__c,gcevent.resource_type__c);
           gcevent.Customer_Email__c = getCustomerEmail(gcevent.Customer_Number__c);
           List <Account> Acc = [SELECT Id from Account where email__c = :gcevent.Customer_Email__c];
           for (integer a=0; a< Acc.size(); a++) {
               if (Acc.size()>0) gcevent.Account__c = Acc[a].Id;
           }
           insert gcevent;
       }
       return 'Done';
	}

    Static String getCustomerNo(String objectId, String Endpoint) {
    
        
        system.debug(objectId);
        String Response;
        String Headers;
        string BaseURL= 'https://api-sandbox.gocardless.com/';
        string Token = 'sandbox_v5Szjx49RSC3H7-OrP5GKTM5emgYmaX9fgYTfCZR';
	    string bearerToken = 'w-AINtjyy0k75CFBeBZbiA9cj4ebQuut-4--HsJp';
        
        // Get the XML document from the external server
        Http http = new Http();
        HttpRequest req = new HttpRequest();
        req.setEndpoint(BaseURL+Endpoint+'/'+objectId);
     	req.setHeader('access_token', 'Bearer '+Token);
        req.setHeader('Authorization', 'Bearer '+Token);
        req.setHeader('GoCardless-Version', '2015-07-06');
        req.setHeader('Content-Type', 'application/json');
        req.setHeader('Accept', 'application/json');
        req.setMethod('GET');
        HttpResponse res = http.send(req);
    	String jSONResponseBody=res.getBody().trim();
        Integer strStart = jSONResponseBody.indexOf('customer":"')+11;
        Integer strend = jSONResponseBody.substring(strStart).indexOf('"');
        String CustNo = jSONResponseBody.substring(strStart, strStart+strend);
        return CustNo;
      }    
    
    Static String getCustomerEmail(String objectId) {
    
        
        system.debug(objectId);
       String Response;
       String Headers;
       string BaseURL= 'https://api-sandbox.gocardless.com/customers/';
       string Token = 'sandbox_v5Szjx49RSC3H7-OrP5GKTM5emgYmaX9fgYTfCZR';
	   string bearerToken = 'w-AINtjyy0k75CFBeBZbiA9cj4ebQuut-4--HsJp';
        
        // Get the XML document from the external server
        Http http = new Http();
        HttpRequest req = new HttpRequest();
        req.setEndpoint(BaseURL+'/'+objectId);
     	req.setHeader('access_token', 'Bearer '+Token);
        req.setHeader('Authorization', 'Bearer '+Token);
        req.setHeader('GoCardless-Version', '2015-07-06');
        req.setHeader('Content-Type', 'application/json');
        req.setHeader('Accept', 'application/json');
        req.setMethod('GET');
        HttpResponse res = http.send(req);
    	String jSONResponseBody=res.getBody().trim();
        Integer strStart = jSONResponseBody.indexOf('email":"')+8;
        Integer strend = jSONResponseBody.substring(strStart).indexOf('"');
        String CustEmail = jSONResponseBody.substring(strStart, strStart+strend);
        return CustEmail;
      }    
    
    
    
    public class ResponseResult {
    
        public Event[] events;

    }
    public class Event {
        public String id, resource_type,action;
        public datetime created_at;
		public objLinks links;          
    }

    public class objLinks{
           string mandate;
           string payment;
        }




}

Test Class
 
@isTest 
public class GoCardlessEndpointsTest {

    
    static testMethod void test_doPost() {
            
            String JSONMsg = '{"events": [{"id": "EV123","email": "barry.denson@hotmail.com", "created_at": "2014-08-04T12:00:00.000Z","action": "cancelled","resource_type": "mandates","links": {"mandate": "MD123"},"details": {"origin": "bank","cause":"bank_account_disabled","description": "Your customer closed their bank account.","scheme": "bacs","reason_code": "ADDACS-B"}},{"id": "EV456","created_at": "2014-08-04T12:00:00.000Z","action": "expired","resource_type": "mandates","links": {"mandate": "MD456"},"details": {"origin": "gocardless","cause": "mandate_expired","description": "The mandate expired due to inactivity."}}]}';
    
            RestRequest req = new RestRequest();
            RestResponse res = new RestResponse();
            
            req.requestURI = '/services/apexrest/gocardless/';  //Request URL
            req.httpMethod = 'POST';							//HTTP Request Type
            req.requestBody = Blob.valueof(JSONMsg);
            
            RestContext.request = req;
            RestContext.response= res;
            
            Test.startTest();
                GoCardlessEndpoints.doPost();
            Test.StopTest();   
    }

}

 
v varaprasadv varaprasad
Hi Barry,

Before this line GoCardlessEndpoints.doPost();

Add beow code and check once : 
 
GoCardlessEndpoints.objLinks obj = new GoCardlessEndpoints.objLinks();
obj.mandate ='TestData';
obj.payment = 'TestPayment';

GoCardlessEndpoints.Event evnt = new GoCardlessEndpoints.Event();
evnt.id = 'id';
evnt.resource_type = 'resource';
evnt.action = 'Creation' ;
evnt.created_at = system.now(); 
evnt.links =  obj;


GoCardlessEndpoints.ResponseResult res = new GoCardlessEndpoints.ResponseResult();
res.events = 'Event Records';


Hope this helps you.

Thanks
Varaprasad
@For Support: varaprasad4sfdc@gmail.com






 
Baz DensonBaz Denson
Hi Varapshad,

Thanks for that help, I now have some errors in my code.


User-added image

Regards

Barry