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
dhanraj rdhanraj r 

How to Cover the test class for batch apex callout

global class CouponBatch implements Database.Batchable<sObject>, Database.AllowsCallouts{
    global Database.QueryLocator start(Database.BatchableContext bc){
        String soqlQuery = 'SELECT id, CouponCode__c, Redeemed_Code__c, Type From order';
        return Database.getQueryLocator(soqlQuery);
    }
     

    global void execute(Database.BatchableContext bc, List<Order> orderDetails){
         
                try {
                    HttpRequest req = new HttpRequest();
                    req.setEndpoint('callout:couponcode_101/couponcode.json');
                    req.setMethod('GET');
                    Http http =  new Http();
                    HttpResponse res = http.send(req);  
                        if (res.getStatusCode() == 200) {
                        Map<String, Object> results = (Map<String, Object>)JSON.deserializeUntyped(res.getBody());
                        List<Object> resultslist = (List<Object>)results.get('discount_codes');
                        for(order datadetails: orderDetails) {
                            for(Object mapa:resultslist ){
                                Map<String,Object> tempMap = (Map<String,Object>)mapa;
                                if(datadetails.CouponCode__c==tempMap.get('code')){
                                    datadetails.Redeemed_Code__c=true;                                   
                                }
    
                            }
                        }      
                       update orderDetails;        
                    }
                }
                catch(Exception e){
                     system.debug('Message: '+e.getMessage());
                        system.debug('Line: '+e.getLineNumber());
                }
            }
   
    global void finish(Database.BatchableContext bc){
     }
}
Best Answer chosen by dhanraj r
ravi soniravi soni
hy Dhanraj,
below is your test class with 95% code coverage.keep one thing in mind that if you need to update your CouponCode__c then must update 
with below line code.
for example if you update your CouponCode__c  in test class with 11111 then it must be update [{"code":"1111"}]
response.setBody('{"discount_codes":[{"code":"055"}]}');
@isTest
public class CouponBatchTest {
@isTest
    public static void test_unit(){
         // Insert Account

    Account a = new Account();
    a.Name = 'Test Account';
    insert a;

       List<Product2> prodList=new List<Product2>();
        prodList.add(new Product2( Name='Test 1', IsActive=true));
        prodList.add(new Product2( Name='Test 2', IsActive=true));
        
        Pricebook2 standardPricebook = new Pricebook2(
            Id = Test.getStandardPricebookId(),
            IsActive = true
        );
        Update standardPricebook;
        
      
        if(prodList.size() > 0){
            insert prodList;   
        }

    
      Pricebook2 customPB = new Pricebook2(Name='Custom Pricebook', isActive=true);
        insert customPB;
   Id pricebookId = Test.getStandardPricebookId();
    
    // Insert PricebookEntry
    
    PricebookEntry standardPrice = new PricebookEntry();
    standardPrice.Pricebook2Id = customPB.Id;
    standardPrice.Product2Id =prodList[0].Id;
    standardPrice.UnitPrice = 1;
    standardPrice.IsActive = true;
    standardPrice.UseStandardPrice = false;
    insert standardPrice ;

    
    // Insert Order
    
    Order o = new Order();
    o.Name = 'Test Order ';
    o.Status = 'Draft';
    o.EffectiveDate = system.today();
    o.EndDate = system.today() + 4;
    o.AccountId = a.id;
    o.Pricebook2Id =  customPB.Id ;
    o.CouponCode__c = '055';
    
    insert o;
        
        test.startTest();
         Test.setMock(HttpCalloutMock.class, new myAnimalLocatorMock()); 
        CouponBatch oCouponBatch = new CouponBatch();
        database.executeBatch(oCouponBatch);
        test.stopTest();
    }
    
     public class myAnimalLocatorMock implements HttpCalloutMock {
    // Implement this interface method
    public HTTPResponse respond(HTTPRequest request) {
        // Create a fake response
        HttpResponse response = new HttpResponse();
        response.setHeader('Content-Type', 'application/json');
        //response.setBody('{"discount_codes":[{"id":1,"name":"chicken","eats":"chicken food","says":"cluck cluck"},{"id":2,"name":"duck","eats":"worms","says":"pek pek"}]}');
        response.setBody('{"discount_codes":[{"code":"055"}]}');
        response.setStatusCode(200);
        return response; 
    }
}
}

don't forget to mark it as best answer.
Thank you

All Answers

SwethaSwetha (Salesforce Developers) 
HI Dhanraj,
The code provided in question does not highlight the uncovered lines. The below articles give a good insight into how coverage can be improved

https://salesforce.stackexchange.com/questions/244794/how-do-i-increase-my-code-coverage-or-why-cant-i-cover-these-lines 

Examples of test class for batch apex callout:
https://salesforce.stackexchange.com/questions/20546/test-class-for-batch-apex-with-webservice-callout

https://salesforce.stackexchange.com/questions/19444/batch-apex-with-webservice-callout?rq=1

https://salesforce.stackexchange.com/questions/130639/test-class-for-batch-that-sends-callout?rq=1

Hope this helps you. Please mark this answer as best so that others facing the same issue will find this information useful. Thank you
dhanraj rdhanraj r

Hi Swetha,

The below section is not covered

                        if (res.getStatusCode() == 200) {
                        Map<String, Object> results = (Map<String, Object>)JSON.deserializeUntyped(res.getBody());
                        List<Object> resultslist = (List<Object>)results.get('discount_codes');
                        for(order datadetails: orderDetails) {
                            for(Object mapa:resultslist ){
                                Map<String,Object> tempMap = (Map<String,Object>)mapa;
                                if(datadetails.CouponCode__c==tempMap.get('code')){
                                    datadetails.Redeemed_Code__c=true;                                   
                                }
    
                            }
                        }      
                       update orderDetails;        
                    }

ravi soniravi soni
hy Dhanraj,
below is your test class with 95% code coverage.keep one thing in mind that if you need to update your CouponCode__c then must update 
with below line code.
for example if you update your CouponCode__c  in test class with 11111 then it must be update [{"code":"1111"}]
response.setBody('{"discount_codes":[{"code":"055"}]}');
@isTest
public class CouponBatchTest {
@isTest
    public static void test_unit(){
         // Insert Account

    Account a = new Account();
    a.Name = 'Test Account';
    insert a;

       List<Product2> prodList=new List<Product2>();
        prodList.add(new Product2( Name='Test 1', IsActive=true));
        prodList.add(new Product2( Name='Test 2', IsActive=true));
        
        Pricebook2 standardPricebook = new Pricebook2(
            Id = Test.getStandardPricebookId(),
            IsActive = true
        );
        Update standardPricebook;
        
      
        if(prodList.size() > 0){
            insert prodList;   
        }

    
      Pricebook2 customPB = new Pricebook2(Name='Custom Pricebook', isActive=true);
        insert customPB;
   Id pricebookId = Test.getStandardPricebookId();
    
    // Insert PricebookEntry
    
    PricebookEntry standardPrice = new PricebookEntry();
    standardPrice.Pricebook2Id = customPB.Id;
    standardPrice.Product2Id =prodList[0].Id;
    standardPrice.UnitPrice = 1;
    standardPrice.IsActive = true;
    standardPrice.UseStandardPrice = false;
    insert standardPrice ;

    
    // Insert Order
    
    Order o = new Order();
    o.Name = 'Test Order ';
    o.Status = 'Draft';
    o.EffectiveDate = system.today();
    o.EndDate = system.today() + 4;
    o.AccountId = a.id;
    o.Pricebook2Id =  customPB.Id ;
    o.CouponCode__c = '055';
    
    insert o;
        
        test.startTest();
         Test.setMock(HttpCalloutMock.class, new myAnimalLocatorMock()); 
        CouponBatch oCouponBatch = new CouponBatch();
        database.executeBatch(oCouponBatch);
        test.stopTest();
    }
    
     public class myAnimalLocatorMock implements HttpCalloutMock {
    // Implement this interface method
    public HTTPResponse respond(HTTPRequest request) {
        // Create a fake response
        HttpResponse response = new HttpResponse();
        response.setHeader('Content-Type', 'application/json');
        //response.setBody('{"discount_codes":[{"id":1,"name":"chicken","eats":"chicken food","says":"cluck cluck"},{"id":2,"name":"duck","eats":"worms","says":"pek pek"}]}');
        response.setBody('{"discount_codes":[{"code":"055"}]}');
        response.setStatusCode(200);
        return response; 
    }
}
}

don't forget to mark it as best answer.
Thank you
This was selected as the best answer
dhanraj rdhanraj r

Hi Veer Soni, 

Thanks for your help. Now code coverage is 90%.