• rayyan m 6
  • NEWBIE
  • 0 Points
  • Member since 2018

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 1
    Replies
Hi ALL,
I am trying to test class for the batch callout class and facing an error and unable to complete the code coverage can someone help me on this and help me get the code coverage.
global class VPS_LoginReminder_Batch_90days implements Database.Batchable<sObject>, Database.AllowsCallouts, Database.Stateful {
    
    
    public string myLabel = System.Label.VPS_Inactive_90Days;
   	public integer myInt = Integer.valueOf(myLabel);  
    
    public string myLabel1 = System.Label.VPS_Inactive_180Days;
   	public integer myInt1 = Integer.valueOf(myLabel1); 

                Datetime myDateTime = system.now();
                Datetime inactivationReminder = myDateTime.addDays(myInt);
				Datetime myDateTime1 = system.now();
                Datetime inactivationReminder1 = myDateTime1.addDays(myInt1);
    
    global final List<User> UserList= new List<User>();
    String response;
    
    global Database.QueryLocator start(Database.BatchableContext BC) { 
        
       
        return Database.getQueryLocator([Select id, LastLoginDate, firstName, lastname, email, Contact.name,FederationIdentifier,VPS_AM_Username__c,Username,VPS_SL_60Days_Submitted__c,IsActive From User 
                                         where LastLoginDate!=null AND IsActive=true AND ((LastLoginDate<: inactivationReminder AND LastLoginDate>=:inactivationReminder1  AND VPS_SL_60Days_Submitted__c=false)) 
                                         AND (firstname like 'Sneha' or firstname like 'Vishnu'  or firstname like 'Tesa' or firstname like 'Nafeeza')]);
       
    }
     
    global void execute(Database.BatchableContext BC, List<User> usrList) {
      
        for(User user:usrList){
            UserList.add(user);
        }
        System.debug('userlist size'+userlist.size()+'userlist'+userlist);
        
       }    
     
    global void finish(Database.BatchableContext BC) {
         VPS_oauth_Authentications__c  VPS_oauth = VPS_oauth_Authentications__c.getOrgDefaults() ;
         Integer UserListSize= UserList.size();
         List<User> usrList=new List<user>();
         VPS_Json_ServiceLayer obj= new VPS_Json_ServiceLayer(UserList,VPS_oauth.VPS_Template_90days__c,VPS_oauth.VPS_APINotificationType_Bulk__c);
         String body= obj.returnJSON();
         system.debug('string body returned'+UserList);
        
       
         // Call Service layer
        HttpRequest req = new HttpRequest();
        req.setMethod(VPS_oauth.Address_API_Method__c);
        req.setHeader('apikey',VPS_oauth.VPS_SL_API_Key_for_BULK_RTM__c);
        req.setHeader('Content-Type',VPS_oauth.Address_Header_Content__c);
        req.setHeader('ENV',VPS_oauth.VPS_ENV__c);
        req.setHeader('CCNA',VPS_oauth.Address_Header_CCNA__c);
        req.setHeader('authType',VPS_oauth.Address_Header_AuthType__c);
        req.setEndpoint(VPS_oauth.VPS_Bulk_Email_API_EndPoint_SL__c);
        req.setClientCertificateName(VPS_oauth.ClientCertificateName__c);
        req.setBody(body);
        system.debug('body'+body);
        system.debug('req'+req);
        Http http = new Http();
        HTTPResponse res = http.send(req);
                                system.debug('res'+res);
            if(res.getStatusCode()==200){
                system.debug('success');
                if(UserList.size()>0){
                    for(User usr:UserList){
                    usr.VPS_SL_60Days_Submitted__c=true; 
                    usrList.add(usr);
                              }
                   }
                
               
                                                                
                VPS_Application_Exception_Log__c v= new VPS_Application_Exception_Log__c();
                v.VPS_LoginReminder_Status__c='SUCCESS';
                v.VPS_LoginReminder_TemplateName__c=VPS_oauth.VPS_Template_90days__c;
                v.VPS_LoginReminder_Date__c=System.now();
                v.VPS_LoginReminder_CountOfRecords__c=UserListSize;
                v.VPS_Apex_Class__c='VPS_LoginReminder_Batch_90days';
               v.VPS_Method__c='Batch Execute';
               insert v;
               update usrList;
              
                                } 
        
        else{
            
            if(UserList.size()>0){
                 system.debug('error');
                    for(User usr:UserList){
                    usr.VPS_SL_60Days_Submitted__c=false; 
                    usrList.add(usr);
                              }
                   }
                                               
               update usrList;
               VPS_Application_Exception_Log__c v= new VPS_Application_Exception_Log__c();
               v.VPS_LoginReminder_Status__c='FAILURE';
               v.VPS_LoginReminder_TemplateName__c=VPS_oauth.VPS_Template_90days__c;
               v.VPS_LoginReminder_ErrorMessage__c=res.getBody();
               v.VPS_LoginReminder_Date__c=System.now();
               v.VPS_LoginReminder_CountOfRecords__c=UserListSize;
               v.VPS_Apex_Class__c='VPS_LoginReminder_Batch_90days';
               v.VPS_Method__c='Batch Execute';
               Insert v; 
             } 
                                

}
}
 
Test class:
@isTest 
public class VPS_LoginReminder_Batch_90days_Test {

  public VPS_oauth_Authentications__c  VPS_oauth = VPS_oauth_Authentications__c.getOrgDefaults() ;    
    public static testMethod void setUp()	{ 
    
    Profile pro= [SELECT Id FROM Profile WHERE Name = 'System Administrator' limit 1];
    List<User> userlist = new List<User>();
    for(Integer i=0;i<20;i++){
        User usr = new User(Alias='Test'+i, LastName='User1'+i, email='dcopeland'+i+'@twcny.com', Username='User'+i+'@infosys.com',
                             TimeZoneSidKey = 'America/Los_Angeles', EmailEncodingKey = 'UTF-8', LanguageLocaleKey = 'en_US',
                             LocaleSidKey = 'en_US', ProfileId =pro.Id);
            userlist.add(usr);  
        SYSTEM.debug('userlistsize::'+userlist);
    }    
            insert userlist;
        SYSTEM.debug('userlistsize::'+userlist);
        List<User> usrlist=[select id,name,FirstName,LastName,email,VPS_AM_Username__c,FederationIdentifier,Username,ContactId,LastLoginDate,VPS_SL_60Days_Submitted__c,VPS_UserStatus__c from user LIMIT 100];
        	VPS_Json_ServiceLayer JsonseviceLayer1=new VPS_Json_ServiceLayer(usrList,'Template_90','BULK');
        	String body=JsonseviceLayer1.returnJSON();
        VPS_oauth_Authentications__c  VPS_oauth = new VPS_oauth_Authentications__c();
       		VPS_oauth.VPS_SL_API_Key_for_BULK_RTM__c='apikey';
            VPS_oauth.Address_Header_Content__c='application/json';
            VPS_oauth.VPS_ENV__c='UAT';
            VPS_oauth.Address_Header_CCNA__c='EPO';
            VPS_oauth.Address_Header_AuthType__c='2WAYSSL';
            VPS_oauth.VPS_Bulk_Email_API_EndPoint_SL__c='My end point i can disclose here ';
            VPS_oauth.ClientCertificateName__c='cxdigital';
        	insert VPS_oauth;   
        
        Test.startTest();
        Database.BatchableContext     bc;
        Test.setMock(HttpCalloutMock.class, new VPS_MockHttpResponseGenerator()); 
        VPS_LoginReminder_Batch_90days batch=new VPS_LoginReminder_Batch_90days();
        Database.executeBatch(batch);
        //callout method to performs the callout
        //batch.finish(bc);
        
        Test.stopTest();
   
    }
   

}
 
@isTest
global class VPS_MockHttpResponseGenerator implements HttpCalloutMock {
    // Implement this interface method
    global HTTPResponse respond(HTTPRequest req) {
      List<User> usrlist=[select id,name,FirstName,LastName,email,VPS_PortalUserId__c,VPS_AM_Username__c,FederationIdentifier from user where LastLoginDate!=null AND IsActive=true limit 100];
      VPS_Json_ServiceLayer obj= new VPS_Json_ServiceLayer(usrlist,'CX_90_DAY','BULK');
        String body= obj.returnJSON();
         // Optionally, only send a mock response for a specific endpoint
        // and method.
        System.assertEquals('ENDpoint URL', req.getEndpoint());
        System.assertEquals('POST', req.getMethod());
        
        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setBody('{ "templateName":"CX_90_DAY","users":[{"firstName":"Abhishek","lastName":"Anand","userId":"ananab7","email":"Anand.Abhishek@gmail.com"},{"firstName":"Veera","lastName":"Kishore","userId":"kumave6","email":"Veera.Kishore@gmail.com"} ] }');
        res.setStatusCode(200);
        return res;
    }
}

 
Hi ALL,
I am trying to test class for the batch callout class and facing an error and unable to complete the code coverage can someone help me on this and help me get the code coverage.
global class VPS_LoginReminder_Batch_90days implements Database.Batchable<sObject>, Database.AllowsCallouts, Database.Stateful {
    
    
    public string myLabel = System.Label.VPS_Inactive_90Days;
   	public integer myInt = Integer.valueOf(myLabel);  
    
    public string myLabel1 = System.Label.VPS_Inactive_180Days;
   	public integer myInt1 = Integer.valueOf(myLabel1); 

                Datetime myDateTime = system.now();
                Datetime inactivationReminder = myDateTime.addDays(myInt);
				Datetime myDateTime1 = system.now();
                Datetime inactivationReminder1 = myDateTime1.addDays(myInt1);
    
    global final List<User> UserList= new List<User>();
    String response;
    
    global Database.QueryLocator start(Database.BatchableContext BC) { 
        
       
        return Database.getQueryLocator([Select id, LastLoginDate, firstName, lastname, email, Contact.name,FederationIdentifier,VPS_AM_Username__c,Username,VPS_SL_60Days_Submitted__c,IsActive From User 
                                         where LastLoginDate!=null AND IsActive=true AND ((LastLoginDate<: inactivationReminder AND LastLoginDate>=:inactivationReminder1  AND VPS_SL_60Days_Submitted__c=false)) 
                                         AND (firstname like 'Sneha' or firstname like 'Vishnu'  or firstname like 'Tesa' or firstname like 'Nafeeza')]);
       
    }
     
    global void execute(Database.BatchableContext BC, List<User> usrList) {
      
        for(User user:usrList){
            UserList.add(user);
        }
        System.debug('userlist size'+userlist.size()+'userlist'+userlist);
        
       }    
     
    global void finish(Database.BatchableContext BC) {
         VPS_oauth_Authentications__c  VPS_oauth = VPS_oauth_Authentications__c.getOrgDefaults() ;
         Integer UserListSize= UserList.size();
         List<User> usrList=new List<user>();
         VPS_Json_ServiceLayer obj= new VPS_Json_ServiceLayer(UserList,VPS_oauth.VPS_Template_90days__c,VPS_oauth.VPS_APINotificationType_Bulk__c);
         String body= obj.returnJSON();
         system.debug('string body returned'+UserList);
        
       
         // Call Service layer
        HttpRequest req = new HttpRequest();
        req.setMethod(VPS_oauth.Address_API_Method__c);
        req.setHeader('apikey',VPS_oauth.VPS_SL_API_Key_for_BULK_RTM__c);
        req.setHeader('Content-Type',VPS_oauth.Address_Header_Content__c);
        req.setHeader('ENV',VPS_oauth.VPS_ENV__c);
        req.setHeader('CCNA',VPS_oauth.Address_Header_CCNA__c);
        req.setHeader('authType',VPS_oauth.Address_Header_AuthType__c);
        req.setEndpoint(VPS_oauth.VPS_Bulk_Email_API_EndPoint_SL__c);
        req.setClientCertificateName(VPS_oauth.ClientCertificateName__c);
        req.setBody(body);
        system.debug('body'+body);
        system.debug('req'+req);
        Http http = new Http();
        HTTPResponse res = http.send(req);
                                system.debug('res'+res);
            if(res.getStatusCode()==200){
                system.debug('success');
                if(UserList.size()>0){
                    for(User usr:UserList){
                    usr.VPS_SL_60Days_Submitted__c=true; 
                    usrList.add(usr);
                              }
                   }
                
               
                                                                
                VPS_Application_Exception_Log__c v= new VPS_Application_Exception_Log__c();
                v.VPS_LoginReminder_Status__c='SUCCESS';
                v.VPS_LoginReminder_TemplateName__c=VPS_oauth.VPS_Template_90days__c;
                v.VPS_LoginReminder_Date__c=System.now();
                v.VPS_LoginReminder_CountOfRecords__c=UserListSize;
                v.VPS_Apex_Class__c='VPS_LoginReminder_Batch_90days';
               v.VPS_Method__c='Batch Execute';
               insert v;
               update usrList;
              
                                } 
        
        else{
            
            if(UserList.size()>0){
                 system.debug('error');
                    for(User usr:UserList){
                    usr.VPS_SL_60Days_Submitted__c=false; 
                    usrList.add(usr);
                              }
                   }
                                               
               update usrList;
               VPS_Application_Exception_Log__c v= new VPS_Application_Exception_Log__c();
               v.VPS_LoginReminder_Status__c='FAILURE';
               v.VPS_LoginReminder_TemplateName__c=VPS_oauth.VPS_Template_90days__c;
               v.VPS_LoginReminder_ErrorMessage__c=res.getBody();
               v.VPS_LoginReminder_Date__c=System.now();
               v.VPS_LoginReminder_CountOfRecords__c=UserListSize;
               v.VPS_Apex_Class__c='VPS_LoginReminder_Batch_90days';
               v.VPS_Method__c='Batch Execute';
               Insert v; 
             } 
                                

}
}
 
Test class:
@isTest 
public class VPS_LoginReminder_Batch_90days_Test {

  public VPS_oauth_Authentications__c  VPS_oauth = VPS_oauth_Authentications__c.getOrgDefaults() ;    
    public static testMethod void setUp()	{ 
    
    Profile pro= [SELECT Id FROM Profile WHERE Name = 'System Administrator' limit 1];
    List<User> userlist = new List<User>();
    for(Integer i=0;i<20;i++){
        User usr = new User(Alias='Test'+i, LastName='User1'+i, email='dcopeland'+i+'@twcny.com', Username='User'+i+'@infosys.com',
                             TimeZoneSidKey = 'America/Los_Angeles', EmailEncodingKey = 'UTF-8', LanguageLocaleKey = 'en_US',
                             LocaleSidKey = 'en_US', ProfileId =pro.Id);
            userlist.add(usr);  
        SYSTEM.debug('userlistsize::'+userlist);
    }    
            insert userlist;
        SYSTEM.debug('userlistsize::'+userlist);
        List<User> usrlist=[select id,name,FirstName,LastName,email,VPS_AM_Username__c,FederationIdentifier,Username,ContactId,LastLoginDate,VPS_SL_60Days_Submitted__c,VPS_UserStatus__c from user LIMIT 100];
        	VPS_Json_ServiceLayer JsonseviceLayer1=new VPS_Json_ServiceLayer(usrList,'Template_90','BULK');
        	String body=JsonseviceLayer1.returnJSON();
        VPS_oauth_Authentications__c  VPS_oauth = new VPS_oauth_Authentications__c();
       		VPS_oauth.VPS_SL_API_Key_for_BULK_RTM__c='apikey';
            VPS_oauth.Address_Header_Content__c='application/json';
            VPS_oauth.VPS_ENV__c='UAT';
            VPS_oauth.Address_Header_CCNA__c='EPO';
            VPS_oauth.Address_Header_AuthType__c='2WAYSSL';
            VPS_oauth.VPS_Bulk_Email_API_EndPoint_SL__c='My end point i can disclose here ';
            VPS_oauth.ClientCertificateName__c='cxdigital';
        	insert VPS_oauth;   
        
        Test.startTest();
        Database.BatchableContext     bc;
        Test.setMock(HttpCalloutMock.class, new VPS_MockHttpResponseGenerator()); 
        VPS_LoginReminder_Batch_90days batch=new VPS_LoginReminder_Batch_90days();
        Database.executeBatch(batch);
        //callout method to performs the callout
        //batch.finish(bc);
        
        Test.stopTest();
   
    }
   

}
 
@isTest
global class VPS_MockHttpResponseGenerator implements HttpCalloutMock {
    // Implement this interface method
    global HTTPResponse respond(HTTPRequest req) {
      List<User> usrlist=[select id,name,FirstName,LastName,email,VPS_PortalUserId__c,VPS_AM_Username__c,FederationIdentifier from user where LastLoginDate!=null AND IsActive=true limit 100];
      VPS_Json_ServiceLayer obj= new VPS_Json_ServiceLayer(usrlist,'CX_90_DAY','BULK');
        String body= obj.returnJSON();
         // Optionally, only send a mock response for a specific endpoint
        // and method.
        System.assertEquals('ENDpoint URL', req.getEndpoint());
        System.assertEquals('POST', req.getMethod());
        
        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setBody('{ "templateName":"CX_90_DAY","users":[{"firstName":"Abhishek","lastName":"Anand","userId":"ananab7","email":"Anand.Abhishek@gmail.com"},{"firstName":"Veera","lastName":"Kishore","userId":"kumave6","email":"Veera.Kishore@gmail.com"} ] }');
        res.setStatusCode(200);
        return res;
    }
}