0

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();
    }
    }

This Portion 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.

5
  • 1
    It seems that the results from start method is none. So Execute method not called in your test method. Insert test data which gives the result when you run the batch class from your test method. Change the Contract End Date in the test data to System.today()+1 and try.
    – Maha
    Apr 26 '16 at 12:45
  • @Maha ,@Vigneshwaran G:Thanks for your response.I have changed the end date but the code got increased with 3% only.The send email message is not getting covered .Any Suggestion very much appreciated. Apr 26 '16 at 13:08
  • 1
    In the Contract test data, you need to specify email address for Contact_Email__c field.
    – Maha
    Apr 26 '16 at 13:24
  • @Maha:Contact_Email__c field is a formula field which is appended from contact.i have given the email field in contact. Apr 27 '16 at 6:20
  • how the contact is linked with the Contract object? Please add specific contact reference field in the Contract insertion test data. Contract contr90 = new Contract(CurrencyIsoCode='USD', Opportunity_Product_Id__c=ooli9.Id,AccountId=acc90.Id,StartDate=System.today() ,EndDate=System.today()); insert contr90;
    – Maha
    Apr 29 '16 at 5:37
1

As @Maha stated, your start method doesn't yield any results to fed to the execute method meaning your Database.getQueryLocator returns no records.

In start method, you query for contracts with end date as tomorrow (Date.today().addDays(1)) but in your test class you create contract with end date as today.

EndDate=System.today()

Change it to

EndDate=System.today().addDays(1)

Hope it helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.