+ Start a Discussion
SalesforceCrm AccountCRMSalesforceCrm AccountCRM 

Help in test class for Batch and Schedule classes

I have a Batch class and written a test class where the code coverage is displaying as 50% only.How to cover the single message email in the test class .
Batch Class :
global class NinetyDaysNotificationEmail implements Database.Batchable < sObject >, Schedulable, Database.Stateful {
    global List<String> errorMessages = new List<String>();
    global Database.QueryLocator start(Database.BatchableContext bc) {

        Date ed = Date.today().addDays(1);
        System.debug(Date.today().addDays(1));

        set<Id> setContractIds = new set<Id>();

        for(Contract_role__c objContract: [SELECT  Contract__c FROM Contract_role__c WHERE Role__c = 'Subscription Administrator' AND Contract__r.EndDate =: ed]) {
            setContractIds.add(objContract.Contract__c);
        }

         return Database.getQueryLocator([Select  id, Contract_Name__c , EndDate ,Contact_Email__c,  Account.Owner.Email ,Account.Owner.Manager.Email,Contact__r.ID FROM Contract  WHERE Id IN: setContractIds ]);
    }

    global void execute(Database.BatchableContext bc, List < Contract > recs) {
        List < Messaging.SingleEmailMessage > mailList = new List < Messaging.SingleEmailMessage > ();
        for (Contract c: recs) {
            if (c.Contact_Email__c != null) {
                List < String > toAddresses = new List < String > ();
                List < String > CcAddresses = new List < String > ();
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
               ccAddresses.add(c.Account.Owner.Email);
                 mail.setCcAddresses(CcAddresses);
                  mail.setTargetObjectId(c.Contact__r.ID);
                  mail.setWhatId(c.Id);
                  mail.setTemplateId('00X4B000000M08W');
                  mail.setSaveAsActivity(false);
                mailList.add(mail);
            }
        }

      Messaging.sendEmail(mailList);

    }

    global void finish(Database.BatchableContext bc) {
        AsyncApexJob aaj = [Select Id, Status, NumberOfErrors, JobItemsProcessed, MethodName, TotalJobItems, CreatedBy.Email from AsyncApexJob where Id =:BC.getJobId()];

        // Send an email to the Apex job's submitter notifying of job completion.
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {aaj.CreatedBy.Email};
        mail.setToAddresses(toAddresses);
        mail.setSubject('JOB Salesforce NotificationEmailtoCustomer Finished: ' + aaj.Status);
        String bodyText='Total Job Items ' + aaj.TotalJobItems + ' Number of records processed ' + aaj.JobItemsProcessed + ' with '+ aaj.NumberOfErrors + ' failures.\n';
        bodyText += 'Number of Error Messages ' + errorMessages.size() + '\n';
        bodyText += 'Error Message' + String.join(errorMessages, '\n');
        mail.setPlainTextBody(bodyText);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }

    global void execute(SchedulableContext SC) {
        NotificationEmailtoAccountExecutive batchable = new NotificationEmailtoAccountExecutive();
        database.executebatch(batchable);
    }
}
Test Class :
@isTest
public class TestNinetyDaysNotificationEmail{
static testMethod void TestNinetyDays()
{
Account acc90 = new Account(Name='Testing NinetyDaysNotificationEmail', BillingStreet='Banjara hills', Industry = 'Banking' );
        insert acc90 ;

        contact cc90 = new contact(FirstName ='Test Contact', LastName ='NinetyDaysNotificationEmail', Role__c='Subscription Administrator',Email='xyz@edb.com',AccountId=acc90.Id);
        insert cc90;

        Opportunity opty90 = new Opportunity(Name = 'Test Oppty NinetyDaysNotificationEmail', StageName ='Proposal/Price Quote', CloseDate = System.Today(),  AccountId = acc90.Id,);
        insert opty90;

        list<OpportunityContactRole> opptyConRolelist90 =  new list<OpportunityContactRole>{
            new OpportunityContactRole(ContactId = cc90.Id, OpportunityId = opty90.Id, IsPrimary = false, Role = 'Subscription Administrator')
        };   
        insert opptyConRolelist90;

product2 p90 = new product2(Name='PostgresPlus',Product_Name1__C='Product - Subscription',IsActive = true, Renewable__c=True);
        insert p90;

        PricebookEntry pbey90 = new PricebookEntry(Product2ID=p90.id, Pricebook2ID= test.getStandardPricebookId(), UnitPrice=50, isActive=true);
        insert pbey90;

        Opportunitylineitem ooli9 = new Opportunitylineitem(OpportunityId = opty90.Id, PricebookEntryId = pbey90.Id, Quantity =4, Start_Date__c = System.today(), End_Date__c =  System.today() + 90); 
  insert ooli9;

        Opportunitylineitem ooli90 = new Opportunitylineitem(OpportunityId = opty90.Id, PricebookEntryId = pbey90.Id, Quantity =4, Start_Date__c = System.today(), End_Date__c =  System.today() + 100,  Parent_Opportunity_Product_Id__c=ooli9.Id);
        insert ooli90;

         Contract contr90 = new Contract(CurrencyIsoCode='USD',   Opportunity_Product_Id__c=ooli9.Id,AccountId=acc90.Id,StartDate=System.today() ,EndDate=System.today());
        insert contr90;

Contract_Role__c contrRole90 = new Contract_Role__c(Role__c='Subscription Administrator' ,Contract__c=contr90.Id);
        insert contrRole90;

        Test.StartTest();
        NinetyDaysNotificationEmail Ninetydays = new NinetyDaysNotificationEmail();
        Database.executebatch(Ninetydays);
        Test.StopTest();
    }   
     Static testMethod void TestNinetyDays90()
    { 
        Test.StartTest();
        NinetyDaysNotificationEmail AE = new  NinetyDaysNotificationEmail();
        String sch = '0 0 23 * * ?'; 
        system.schedule('Test Notification email to Customer', sch, AE); 
        //Database.executebatch(b);
        Test.StopTest();
    }
    }
The portion which is not getting covered in DC :
global void execute(Database.BatchableContext bc, List < Contract > recs) {
            List < Messaging.SingleEmailMessage > mailList = new List < Messaging.SingleEmailMessage > ();
            for (Contract c: recs) {
                if (c.Contact_Email__c != null) {
                    List < String > toAddresses = new List < String > ();
                    List < String > CcAddresses = new List < String > ();
                    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                   ccAddresses.add(c.Account.Owner.Email);
                     mail.setCcAddresses(CcAddresses);
                      mail.setTargetObjectId(c.Contact__r.ID);
                      mail.setWhatId(c.Id);
                      mail.setTemplateId('00X4B000000M08W');
                      mail.setSaveAsActivity(false);
                    mailList.add(mail);
                }
            }

          Messaging.sendEmail(mailList);

        }
Any help very much appreciated.