When testing HTTP callouts in Apex, I generally have a Helper Class, with static methods which returns the response I am expecting from the webservice, and in my code, where the http.send();
would normally go, I use this instead.
HTTPResponse resp;
if(!Test.isRunningTest())
{
resp = http.send(req);
}
else
{
resp = MockApiCalls.WebserviceExpectedResponse();
}
Mock Calls class Example
public class MockApiCalls
{
public static HttpResponse WebserviceExpectedResponse()
{
HttpResponse httpResponse = new HttpResponse();
httpResponse.setStatusCode(200);
httpResponse.setBody('{"message":"success","cost":0.09600000000000000}');
return httpResponse;
}
}
I know this isn't particularly clean, but unfortunately this seems to be the only way to properly test http callouts for now. There seem to be improvement coming in the future, in the last release they included Testing Web Service Callouts but you still get the problems you are facing
System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out
This is because in test deployments, all tests still run in one context, and you run into the Cannot do a DML statement before doing a webservice callout problem.
Second Option
This only works when you only have 1 webservice callout to test in your entire test code.
You can name your test class which does the webservice testing AAATestClass
. Which causes your test to be executed before all the rest, and you don't run into the earlier mentioned problem. This is because tests are ordered by test class alphabetically and executed in that order.
Turns out because the apex service was being served from a Sandbox instead of production, Chrome was automatically canceling the request because of a certificate name mismatch error.
From the Salesforce Sites Implementation Guide:
Only production organizations have the valid secure.force.com SSL
certificates to access sites using HTTPS. Note: If a site within a
sandbox (non-production) organization is accessed using HTTPS, a
certificate name mismatch warning may appear
Best Answer
In order to test the callout you should implement a
HttpCalloutMock
(official doc) to emulate the remote service, then set it in your test classRegarding to read the XML response, I recommend you to use de
Dom
class (official doc)Sample of how to read the response: