function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Stefano AmentaStefano Amenta 

Test Class for Apex Batch with http callout

Hi,

I wrote a simple batch that deletes old reports by using the endpoint /services/data/v44.0/analytics/reports/ (which I stored in a custom label).

Now I'm struggling to write the test class code for the batch below.

Which code could I use to test my batch?

Thanks in advance.
 
global class DeleteOldReportsBatch implements Database.Batchable<sObject>, Database.AllowsCallouts {

    //Get the records to be deleted
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = 'select id, FolderName from Report where LastRunDate <= LAST_N_DAYS:60 and FolderName = \'Public Reports\' ';
        return Database.getQueryLocator(query);        
    }

    //Executes the deletion logic for reports records
    global void execute(Database.BatchableContext BC, List<Report> scope) {
    String url;

    for(Report r : scope) {                
            Http h = new Http();
            url = System.Label.ReportsApi + r.Id;
            System.debug(LoggingLevel.INFO, '*** url: ' + url);          

            HttpRequest req = new HttpRequest();

            req.setHeader('Authorization', 'Bearer '+ UserInfo.getSessionId());
            req.setMethod('DELETE');
            req.setEndpoint(url);

            HttpResponse res = h.send(req);
            System.debug(LoggingLevel.INFO, '*** rest: ' + res.getBody());        
        } 
    }

    global void finish(Database.BatchableContext BC) {}
}

 
Best Answer chosen by Stefano Amenta
edanna kedanna k
Hello Stefano Amenta,

You can refer https://salesforce.stackexchange.com/questions/241980/test-class-with-batch-and-callout. It may help you!
If not please let me know!

Regards,
Edanna.

All Answers

edanna kedanna k
Hello Stefano Amenta,

You can refer https://salesforce.stackexchange.com/questions/241980/test-class-with-batch-and-callout. It may help you!
If not please let me know!

Regards,
Edanna.
This was selected as the best answer
Deepali KulshresthaDeepali Kulshrestha
Hi Stefano,

You have to specify the values of the fake response, instruct the Apex runtime to send this fake response by calling Test.setMock in your test method

global class YourHttpCalloutMockImpl implements HttpCalloutMock {
    global HTTPResponse respond(HTTPRequest req) {
        // Create a fake response.
        // Set response values, and 
        // return response.
    }
}
})

I suggest you go through this link, it will help you to understand 

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_testing_httpcalloutmock.htm


I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha.