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
Sanchi9Sanchi9 

Test class for Batch callout

Hi, I want to write a test class for Batch Callout. The code is below:

global class BatchSync implements Database.Batchable<sObject>, Database.AllowsCallouts{
     
    global Database.QueryLocator start(Database.BatchableContext bc){
    
        String query = 'SELECT id, Name, Type From Account WHERE Type='Prospect';
       
        return Database.getQueryLocator(query);
    }
     
    
    global void execute(Database.BatchableContext bc, List<Account> scope){
         
       for (Account acc : scope){  
         
                try{
                    HttpRequest request = new HttpRequest();
                    HttpResponse response = new HttpResponse();
                    Http http = new Http();                    
                    String username = 'Username';
                    String password = 'Password';
                    Blob headerValue = Blob.valueOf(username + ':' + password);
                    String authorizationHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue);
                     
                    request.setHeader('Authorization', authorizationHeader);
                    request.setHeader('Content-Type', 'application/json');
                          
                    request.setEndpoint(enpointurl);
                    request.setMethod('GET');
                    response = http.send(request);                      
                        if (response.getStatusCode() == 200) {
                        String jsonResponse = response.getBody();                                           acc.Type='Customer';
                        
                    }
                    JSONParser parser = JSON.createParser(response.getBody());
                    HttpResponse res = http.send(request);
                    //list of header names keys
                    string[] headerkeys = res.getHeaderKeys();
                    Map<string, string> headers = new map<string, string>();
            
                    //iterate through they keys, and populate your map
                    for(string s : headerkeys){
                    headers.put(s,res.getHeader(s));
                    system.debug('header: ' + s + ' value: ' + res.getHeader(s));
                    }
                    }
                     
                                   
                catch(Exception e){
                   System.debug('Error-' + e.getMessage());   
                } 
                      update scope;
                        }
        }
                   
            
        
    }
 
    global void finish(Database.BatchableContext bc)
    { 
         
    }
}
Best Answer chosen by Sanchi9
Maharajan CMaharajan C
If your class is having HttpRequests then you have to create the HttpCalloutMock class.

First create the below mock class:
 
@isTest
global class BatchSyncMock implements HttpCalloutMock {
    global HTTPResponse respond(HTTPRequest req) {
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setBody('Success');
        res.setStatusCode(200);
        return res;
    }
}

Test class:
 
@istest 
public class BatchSyncTest {
    @isTest static void testbarchClass(){
        List<Account> accList = new List<Account>();
        
        for(integer i = 0 ; i < 5 ;i++ ){
            accList.add(new Account(Name = 'Test Account ' + i , Type ='Prospect'));
        }
        
        if(!accList.isEmpty())
            insert accList;
        
        Test.setMock(HttpCalloutMock.class, new BatchSyncMock());
        
        BatchSync bs = new BatchSync();

        Test.startTest();
        	database.executeBatch(bs,200);
        Test.stopTest();
    }
}

Actual Batch Class:
 
global class BatchSync implements Database.Batchable<sObject>, Database.AllowsCallouts{
    
    global Database.QueryLocator start(Database.BatchableContext bc){
        
        String query = 'SELECT id, Name, Type From Account WHERE Type=\'Prospect\'';
            
            return Database.getQueryLocator(query);
    }
    
    
    global void execute(Database.BatchableContext bc, List<Account> scope){
        
        for (Account acc : scope){  
            
            try{
                HttpRequest request = new HttpRequest();
                HttpResponse response = new HttpResponse();
                Http http = new Http();                    
                String username = 'Username';
                String password = 'Password';
                Blob headerValue = Blob.valueOf(username + ':' + password);
                String authorizationHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue);
                
                request.setHeader('Authorization', authorizationHeader);
                request.setHeader('Content-Type', 'application/json');
                
                String enpointurl = 'https://maharajlwc-dev-ed.my.salesforce.com';
                request.setEndpoint(enpointurl);
                request.setMethod('GET');
                response = http.send(request);                      
                if (response.getStatusCode() == 200) {
                    String jsonResponse = response.getBody();                                           
                    acc.Type='Customer';
                    
                }
                JSONParser parser = JSON.createParser(response.getBody());
                HttpResponse res = http.send(request);
                //list of header names keys
                string[] headerkeys = res.getHeaderKeys();
                Map<string, string> headers = new map<string, string>();
                
                //iterate through they keys, and populate your map
                for(string s : headerkeys){
                    headers.put(s,res.getHeader(s));
                    system.debug('header: ' + s + ' value: ' + res.getHeader(s));
                }
            }
            
            
            catch(Exception e){
                System.debug('Error-' + e.getMessage());   
            } 
            update scope;
        }
    }
    
    global void finish(Database.BatchableContext bc)
    { 
        
    }
}

Thanks,
Maharajan.C