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.setCompressed(true); // otherwise we hit a limit of 32000

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


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



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()) {
| improve this answer | |
  • Reading your links I see how to create a fake response, but how can I get the real one and test it this works? – tony danza Feb 3 '14 at 15:53
  • You could select any public service to test your callout, google is your friend: google.es/search?q=public%20xml%20weather%20feed , sample: query.yahooapis.com/v1/public/… – Martin Borthiry Feb 3 '14 at 16:09
  • @Martin I don't think you can do actual callouts in test execution context. Tony, this is to make sure your tests are reliable and won't fail if the external system fails. – Samuel De Rycke Feb 3 '14 at 16:12
  • What I mean is: I need to make a call to a service I know in apex. How can I see if my call works. – tony danza Feb 3 '14 at 16:15
  • @Sdry: of course you cant. I thought he is trying to test the code on a real external service by user trigged execution context (ex sandbox). – Martin Borthiry Feb 3 '14 at 16:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.