+ Start a Discussion
Dagny FernandesDagny Fernandes 

Batch Class test class coverage logic based on created date

Hi All,

I am not able cover single line of code for the batch class am I makeing anything wrong and the batch class is logic is based on Created Date.

Batch Class:
global class BatchClassToCloseAdSalesOpportunitys implements Database.Batchable<sObject> , Schedulable {
	
	private String OppClosedWon		= Constant_PicklistVariables.OPP_CLOSED_WON;
    private String OppClosedLost	= Constant_PicklistVariables.OPP_CLOSED_LOST;
    //Opportunity Ad Sales RecordType ID
    ID AdSalesRecordTypeId 			= Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('AD-Sales').getRecordTypeId();
    private String query 			= 'Select Id,Name,RecordTypeId,StageName,CreatedDate,Extend__c from Opportunity WHERE RecordTypeId =: AdSalesRecordTypeId AND ( StageName !=: OppClosedWon OR StageName !=: OppClosedLost ) ';
   	
	global BatchClassToCloseAdSalesOpportunitys(){
    	// Batch Constructor
    }
    
    global void execute(SchedulableContext sc) {
    	System.debug('DagnyQuery==>'+query);
        Database.executebatch(this); 
    }
    
    // Start Method
    global Database.QueryLocator start(Database.BatchableContext BC){
    	System.debug('Dagny==>Query==>'+query);
    	return Database.getQueryLocator(query);
    }
  
   	// Execute Logic
   	global void execute(Database.BatchableContext BC, List<sObject>scope){
          Set<Id> oppIdSet						= new Set<Id>();
          list<Opportunity> opportunityList = (list<Opportunity>) scope;
          List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
          map<Id,Integer> campMapList	= new map<Id,Integer>();
          String baseUrl = System.URL.getSalesforceBaseUrl().toExternalForm();

          if(opportunityList.size() > 0){
          	 for(Opportunity oppId: opportunityList){
          	 	oppIdSet.add(oppId.Id);	          	 	
          	 }
          	 
          	 for(ADs_Campaign__c camp: [SELECT Id, Opportunity__c FROM ADs_Campaign__c WHERE Opportunity__c IN: oppIdSet]){
          	 	if(camp.Opportunity__c != null){
	          	 	if(campMapList.containsKey(camp.Opportunity__c)){
	          	 		campMapList.put(camp.Opportunity__c,campMapList.get(camp.Opportunity__c)+1 );
	          	 	}else{
	          	 		campMapList.put(camp.Opportunity__c, 1);
	          	 	}
          	 	}
          	 }
          	 
             for(Opportunity oppRec: opportunityList){
             	DateTime sT 			= oppRec.CreatedDate;
				Date sDate 				= date.newinstance(sT.year(), sT.month(), sT.day());
             	Date startDate 			= sDate;
				Date dueDate 			= System.today();
				Integer numberDaysDue 	= startDate.daysBetween(dueDate);
				Integer timeStamp		= Integer.valueOf(System.Label.OpportunityCloseTimeStamp);
				
				if(oppRec.Extend__c == true){
					if(numberDaysDue >= timeStamp+5){
						if( campMapList.get(oppRec.Id) != null && campMapList.get(oppRec.Id) > 0 ){
							oppRec.StageName = Constant_PicklistVariables.OPP_CLOSED_WON;
						}else{
							oppRec.StageName = Constant_PicklistVariables.OPP_CLOSED_LOST;
						}
						
					}
				}else{
					if(numberDaysDue >= timeStamp){
						if( campMapList.get(oppRec.Id) != null && campMapList.get(oppRec.Id) > 0){
							oppRec.StageName = Constant_PicklistVariables.OPP_CLOSED_WON;
						}else{
							oppRec.StageName = Constant_PicklistVariables.OPP_CLOSED_LOST;
						}
					}else{
						if(numberDaysDue >= timeStamp-2){
							messaging.singleEmailMessage mail = new messaging.singleEmailMessage();
     						mail.ToAddresses = new string[]{ oppRec.CreatedBy.Email};
							// mail.setReplyTo('');   // <-----------------------------------Set the ReplyTo---
						    mail.setSubject('Opprtunity Closur Notification'+oppRec.Name);
						    mail.setUseSignature(false);
							string htmlBody = '<div style="border:2px solid green; border-radius:15px;"><p>Hi,</p><p><span style="color:brown; font-weight:bolder;">'+oppRec.Owner.Name+'</span> ,</p>'
						    +'<p>The Opportunity '+oppRec.Name+'aginst the seller '+oppRec.Account+'</br>!</p> will be closed with in 2 days </br>Please confirm, If you want to extend the opportunity closure For 5 days more </p>'
						    +'<p>Please click on the below link and update the value of "Request For Closure Extension" to checked </br></p>'
						    +'<p>'+baseUrl+'/'+oppRec.Id+' </p></div>';
						
						    mail.setHtmlBody(htmlBody);
						    mails.add(mail);
    					    
						}
					}
					
				}
             }
             System.debug('Dagny==>OpportunityList=>'+opportunityList);
             update opportunityList;
             if(mails.size() > 0 ){
             	Messaging.sendEmail(mails);
             }
          }   
 
   	}
 
   	global void finish(Database.BatchableContext BC){
        // Logic to be Executed at finish
   	}
   
}

Test Class:
@isTest(seeAllData=false)
public class BatachClassToCloseAdSalesOppty_Test {
	Static User testUser;
    Static Opportunity testOpp;
    Static Opportunity testOpp2;
    static ADs_Campaign__c adsCampaign;
    static ADs_Campaign__c adsCampaign2;
    public BatachClassToCloseAdSalesOppty_Test(){
        
    }
    
    Static void init(){
        testUser 	= InitialTestData2.createUserRecord();
        insert testUser;  
             
        
        DateTime oppCreatDate = System.now() - 15;
        system.debug('oppCreatDate'+oppCreatDate);
        String OppDate = ''+oppCreatDate.formatGMT('yyyy-MM-dd\'T\'HH:mm:ss.SSS\'Z\''+'');
        String oppCreDateStr = String.valueOf(OppDate);
        system.debug('oppCreDateStr'+oppCreDateStr);
        String oppJSON = '{"attributes":{"type":"Opportunity","url":"/services/data/v25.0/sobjects/Opportunity/006N0000005t0cd"},"Id":"006N0000005t0cd","CreatedDate":"'+oppCreDateStr+'"}';
        testOpp = (Opportunity)JSON.deserialize(oppJSON,Opportunity.class);
        
        /*DateTime oppCreatDate2 = System.now() - 13;
        String OppDate2 = ''+oppCreatDate2.formatGMT('yyyy-MM-dd\'T\'HH:mm:ss.SSS\'Z\''+'');
        String oppCreDateStr2 = String.valueOf(OppDate2);
        String oppJSON2 = '{"attributes":{"type":"Opportunity","url":"/services/data/v25.0/sobjects/Opportunity/006N0000006KDab"},"Id":"006N0000006KDab","CreatedDate":"'+oppCreDateStr2+'"}';
        testOpp2 = (Opportunity)JSON.deserialize(oppJSON2,Opportunity.class);*/
        
        system.debug('oppCreDateStr'+testOpp.Id);
        adsCampaign = InitialTestData2.createAdsCampaign(testOpp.Id);
        //insert adsCampaign;
        
        /*adsCampaign2 = InitialTestData2.createAdsCampaign(testOpp2.Id);
        insert adsCampaign2;*/
        
        
    }
    
    //this method is for the Opportunity Batch auto close status update 
    private static testMethod void batchTest (){
    	test.startTest();
        init();
        Database.QueryLocator QueryLoc;
        Database.BatchableContext BatchCont;
        System.runAs(testUser){
            List<Opportunity> oppList = new List<Opportunity>();
            oppList.add(testOpp);
            //oppList.add(testOpp2);
            
            system.debug('List->'+oppList);
            BatchClassToCloseAdSalesOpportunitys batch12 =new BatchClassToCloseAdSalesOpportunitys();
            ID batchprocessid = Database.executeBatch(batch12,200);
            
            QueryLoc= batch12.start(BatchCont);
            System.debug(BatchCont);
            Database.QueryLocatorIterator QueryIterate = QueryLoc.iterator();
            while (QueryIterate.hasNext()){
                 Opportunity objQueue = (Opportunity)QueryIterate.next();           
                 System.debug(objQueue);
                 oppList.add(objQueue);
            }       
            
            batch12.execute(BatchCont, oppList);
            batch12.finish(BatchCont); 
        }
        Test.stopTest();
    }
}

Need Help ASAP,

Thank you in advance.
Andy BoettcherAndy Boettcher
Are you getting any errors when running your test class?
Dagny FernandesDagny Fernandes
Thanks for the quick responce @Andy.

There are no error.