Tuesday, June 11, 2013

In Salesforce, if you are trying to perform a Web Service Callout in a test class, you will get an error. For example:

  1. public String sendHttpRequest(String endpointUrl, String method, DOM.Document body) {
  2.   ...
  3.   HttpRequest req = new HttpRequest();
  4.   req.setEndpoint(endpointUrl);
  5.   req.setMethod(method);
  6.   req.setBody(bodyStr);

  7.   Http http = new Http();
  8.   HttpResponse res = http.send(req);

  9.   return res.getBody();
  10. }

When your test class runs untill line #9, it will stop the entire test process by throwing the following error:

System.TypeException: Methods defined as TestMethod do not support Web service callouts, test skipped callout

What if the overall test coverage is still under 75%? This will become a roadblock for your deployment. Below is the workaround you can consider:

  1. public String sendHttpRequest(String endpointUrl, String method, DOM.Document body, Boolean isTest) {
  2.   ...
  3.   HttpRequest req = new HttpRequest();
  4.   req.setEndpoint(endpointUrl);
  5.   req.setMethod(method);
  6.   req.setBody(bodyStr);

  7.   Http http = new Http();
  8.   if(isTest) {
  9.     HttpResponse res = http.send(req);
  10.     return res.getBody()
  11.   } else {
  12.     // You can prepare some simulated data for your test class here
  13.     return simulatedData;
  14.   }
  15. }

By doing this, you can write different execution as below:

  • Actual Process:
    • You can call the sendHttpRequest method and set the isTest parameter to false.
      • sendHttpRequest(‘your endpoint’, get, ‘http request body’, false);
  • Test Process:
    • In the test process, all you need to do is just set isTest to true.
      • sendHttpRequest(‘your endpoint’, get, ‘http request body’, true);
-->

No comments:

Post a Comment