In Salesforce, if you are trying to perform a Web Service Callout in a test class, you will get an error. For example:
- public String sendHttpRequest(String endpointUrl, String method, DOM.Document body) {
- ...
- HttpRequest req = new HttpRequest();
- req.setEndpoint(endpointUrl);
- req.setMethod(method);
- req.setBody(bodyStr);
- Http http = new Http();
- HttpResponse res = http.send(req);
- return res.getBody();
- }
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:
- public String sendHttpRequest(String endpointUrl, String method, DOM.Document body, Boolean isTest) {
- ...
- HttpRequest req = new HttpRequest();
- req.setEndpoint(endpointUrl);
- req.setMethod(method);
- req.setBody(bodyStr);
- Http http = new Http();
- if(isTest) {
- HttpResponse res = http.send(req);
- return res.getBody()
- } else {
- // You can prepare some simulated data for your test class here
- return simulatedData;
- }
- }
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