[SalesForce] Calling an external REST service in apex

I need to make a call to an external xml-rpc service in apex. I have written this little apex code:

public static void callPBA() {

    HttpRequest req = new HttpRequest();
    HttpResponse res = new HttpResponse();
    Http http = new Http();

    req.setEndpoint('https://external.service.com');
    req.setMethod('POST');
    req.setBody('');
    req.setCompressed(true); // otherwise we hit a limit of 32000

    try {
        res = http.send(req);
    } catch(System.CalloutException e) {
        System.debug('Callout error: '+ e);
        System.debug(res.toString());
    }

}

but I don't know how to test it. Any ideas?
And how can I set the body to read from an xml file?

Thanks.

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 class

Test.setMock(HttpCalloutMock.class, new YourHttpCalloutMockImpl());

Regarding to read the XML response, I recommend you to use de Dom class (official doc)

Sample of how to read the response:

        HttpResponse res = h.send(req);
        Dom.Document doc = res.getBodyDocument();

        //Retrieve the root element for this document.
        Dom.XMLNode address = doc.getRootElement();

        String name = address.getChildElement('name', null).getText();
        String state = address.getChildElement('state', null).getText();
        // print out specific elements
        System.debug('Name: ' + name);
        System.debug('State: ' + state);

        // Alternatively, loop through the child elements.
        // This prints out all the elements of the address
        for(Dom.XMLNode child : address.getChildElements()) {
           System.debug(child.getText());
        }