0

Hi I am writing test class for callouts class any one help on this.

This is my code:

public class recoverrecords{

public static string response;
public static list<string> first = new List<string>();
public static list<string> last = new List<string>();
public static list<string> com = new List<string>();
public static list<lead> lead = new list<lead>();
public static lead l = new lead();

public static void recover(){

http http = new http();
httpRequest request = new httpRequest();
request.setEndpoint('https://ap1.salesforce.com/services/data/v29.0/queryAll/?q=SELECT+firstname,+lastname,+company+from+lead+WHERE+isDeleted+=+True');
request.setMethod('GET');
string Access_Token = userinfo.getsessionid();
request.setHeader('Authorization','Authorization: Bearer '+Access_Token);
request.setTimeout(60000);
HttpResponse res = http.send(request);
response=res.getbody();
system.debug('response:'+response);
string firstname;
string lastname;
string company;

JSONParser parser= JSON.createParser(res.getBody());

while (parser.nextToken() != null)
{
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&(parser.getText() == 'firstname')) {
parser.nextToken();
firstname= parser.gettext()+'\n';
 first.add(firstname);
system.debug('firstname:'+firstname);
}
else if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&(parser.getText() == 'lastname')) {
parser.nextToken();
lastname= parser.gettext()+'\n';
last.add(lastname);
system.debug('lastname:'+lastname);
}
else if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&(parser.getText() == 'company')) {
parser.nextToken();
company= parser.gettext()+'\n';
com.add(company);
system.debug('company:'+company);
}
}
for (Integer i = 0; i < 4; i++) {
    lead.add(new Lead(
            firstname = first[i],
            lastname = last[i],
            company = com[i]
            ));
}
insert lead;
system.debug('lead:'+lead);
}
}

this is my HttpCalloutMock class:

@isTest
global class MockHttpResponseGenerator implements HttpCalloutMock {

    global HTTPResponse respond(HTTPRequest req) {

        System.assertEquals('https://ap1.salesforce.com/services/data/v29.0/queryAll/?q=SELECT+firstname,+lastname,+company+from+lead+WHERE+isDeleted+=+True', req.getEndpoint());
        System.assertEquals('GET', req.getMethod());
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setStatusCode(200);
        return res;
        }
    }

this is my response: {"attributes":{"type":"Lead","url":"/services/data/v29.0/sobjects/Lead/00Q9000000wqxEcEAI"},"FirstName":"s","LastName":"ab","Company":"cccc"},{"attributes":{"type":"Lead","url":"/services/data/v29.0/sobjects/Lead/00Q9000000wqhpoEAA"},"FirstName":"r","LastName":"sfdc","Company":"acuve"}]}

5
  • 2
    You need to use HttpCalloutMock for test class developer.salesforce.com/docs/atlas.en-us.apexcode.meta/…
    – Ratan Paul
    Commented Feb 16, 2016 at 7:43
  • without using HttpCalloutMock i m tring is it correct way?
    – user321
    Commented Feb 16, 2016 at 9:03
  • No you have to use HttpCalloutMock else you will encounter with error Methods defined as TestMethod do not support Web service callouts
    – Ratan Paul
    Commented Feb 16, 2016 at 9:10
  • thank you for responding now i updated httpcalloutmock class help me writing test class
    – user321
    Commented Feb 16, 2016 at 9:22
  • Hi i posted my response could you please tell me how to to take these response in HttpCalloutMock
    – user321
    Commented Feb 16, 2016 at 13:47

1 Answer 1

1

In your implementation of a testmethod to test code that does a callout you need to set the body of the response so that when the underlying code that is being tested makes the callout, the SFDC test framework returns an HTTP response including a statusCode and a body.

There are two ways to set the body as documented in the Apex Developer doc: setBody() and setStaticResource().

Since you are returning a complex JSON string, it is usually easier to choose the setStaticResource() approach as that allows you to use an external text editor to easily create a bunch of JSON responses you want to be able to handle while using JsonLint or the like to validate the mocked responses.

so ...

@isTest
private static void myTestofCodeThatDoesCallout() {


  StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
  mock.setStaticResource('nameofStaticResourceWithMyJsonResponseBody');
  mock.setStatusCode(200);
  mock.setHeader('Content-Type', 'application/json');

  Test.setMock(HttpCalloutMock.class, mock);
  RecoverRecords rr = new RecoverRecords();
  rr.recover();  // SFDC will respond to the callout with mock response
  system.assert(...);  // verify leads are built as expected, errors handled
} 

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .