0

I'm looking to run a scheduled apex batch class that will create a task on any Contact record that had a sales rep assigned to them 1 day ago that hasn't been emailed yet.

I've created 2 custom fields to filter the criteria above.. the date the Contact was assigned a sales rep Sales_Rep_Updated__c and a checkbox field that will be checked as soon as an Email task is completed, Welcome_Email_Sent__c

Here is my Schedulable Batch Class

global class Followup24Email Implements Schedulable, Database.Batchable<sObject>{
global void execute(SchedulableContext sc) {
    Database.executeBatch(this);
}

//This is the query that is passed to the execute method.  It queries all of the Contacts who have passed
String query = 'Select Id, AccountId, OwnerId, Sales_Rep_Updated__c FROM Contact WHERE Sales_Rep_Updated__c = YESTERDAY AND Welcome_Email_Sent__c = FALSE';

global database.queryLocator start(Database.BatchableContext BC) {
    return database.getQueryLocator(query);

} //close start method

global void execute(Database.BatchableContext BC, list <Contact> scope) {

    List <Task> taskList = new List<Task>();

    // Iterate through the whole query of Contacts
    // Create a Task that's associated with each Contact.
    for(Contact c : scope) {
            Task tsk             = new Task();
            tsk.OwnerId          = c.OwnerId;
            tsk.WhoId            = c.Id;
            tsk.WhatId           = c.AccountId;
            tsk.ActivityDate     = System.today();
            tsk.Status           = 'Open';
            tsk.Priority         = 'Normal';
            tsk.Subject          = 'Send Welcome Email';
            tsk.Description      = 'This Account was recently assigned to you, please send them a welcome email.';
            tsk.Type             = 'Email';
            tsk.IsReminderSet    = true;
            tsk.ReminderDateTime = System.now();

            taskList.add(tsk);
    } //close for-loop

    try {
        insert taskList;
    } catch (system.dmlexception e) {
        System.debug('Tasks not inserted: ' + e);
    }
} //close execute method

global void finish(Database.BatchableContext BC) {


} //close finish method
}

And here is my Test class - currently getting 92% (24/26) code coverage

@isTest
private class Followup24EmailTest {

static testMethod void TestFollowup24Email() {

// User Id's for the two sales managers.
String aId = '00561000001DTdh';

List <Contact> contacts = new List <Contact>();
List <Task> tasks = new List <Task>();

// Create 50 Contacts

for (integer i=0; i<50; i++) {
Contact c = new Contact(FirstName='Test',
            LastName='Contact'+ i,
            Sales_Rep_Updated__c = Date.today().addDays(-1),
            Welcome_Email_Sent__c = false,
            OwnerId = aId);
contacts.add(c);

} //close for-loop

insert contacts;

Test.StartTest();

// Call the Batch Apex method.
Followup24Email fue = new Followup24Email();
ID batchprocessid = Database.executeBatch(fue);

Test.StopTest();

List<Task> taskResult = [SELECT ID From TASK];
System.debug('taskResult' + taskResult.size());
/*AsyncApexJob async = [Select Id, Status, NumberOfErrors, JobItemsProcessed,     TotalJobItems from AsyncApexJob where Id = :batchprocessid];
System.debug('Final results are ' + async);

System.AssertEquals(async.NumberOfErrors, 0);
System.AssertEquals([Select count() from Contact Where OwnerId=:aId AND    FirstName='Test'], 50);
System.AssertEquals([Select count() from Task Where Subject = 'Send Welcome    Email'], 50);*/

} //close testmethod

} //close Class

I've created a few test Accounts / Contacts with criteria that should fit (Welcome Email Sent = unchecked, and a Sales Rep Update date of yesterday) but no tasks are ever created.


Edit:

Here is what's not getting covered in my test enter image description here

Any ideas? Thanks!

  • You're scheduling this through apex? – EricSSH Apr 15 '16 at 18:54
  • I'd like to do it through the UI if possible, maybe that's where I've gone wrong? – AJ47 Apr 15 '16 at 18:57
  • No that's fine.. Why are you building Tasks in your test data? – EricSSH Apr 15 '16 at 18:58
  • are you sure that Welcome_Email_Sent__c == false? also doing system.debug during an exception just swallows the error.. not best behaviour – Benjamin Pirih Apr 15 '16 at 18:59
  • @EricSSH good call, lol I'm a bit brain dead today.. I'll remove that part and just insert the contacts. – AJ47 Apr 15 '16 at 19:03
1

I would do something like this for your tests and work from there

@isTest
private class Followup24EmailTest {

static testMethod void TestFollowup24Email() {

// User Id's for the two sales managers.
String aId = '00561000001DTdh';

List <Contact> contacts = new List <Contact>();
List <Task> tasks = new List <Task>();

// Create 50 Contacts and assign them to the sales manager of the opposite location.

for (integer i=0; i<50; i++) {
    Contact c = new Contact(FirstName='Test',
                LastName='Contact'+ i,
                Sales_Rep_Updated__c = Date.today().addDays(-1),
                Welcome_Email_Sent__c  = false,
                OwnerId = aId);
    contacts.add(c);

} //close for-loop

insert contacts;

Test.StartTest();

// Call the Batch Apex method.
Followup24Email fue = new Followup24Email();
ID batchprocessid = Database.executeBatch(fue);

Test.StopTest();

List<Task> taskResult = [SELECT ID From TASK];
System.debug('taskResult' + taskResults.size());
/*AsyncApexJob async = [Select Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems from AsyncApexJob where Id = :batchprocessid];
System.debug('Final results are ' + async);

System.AssertEquals(async.NumberOfErrors, 0);
System.AssertEquals([Select count() from Contact Where OwnerId=:aId AND FirstName='Test'], 50);
System.AssertEquals([Select count() from Task Where Subject = 'Send Welcome Email'], 50);*/

} //close testmethod

} //close Class
  • perhaps mocking the user would be best practice here; as well as asserting the # of tasks – cropredy Apr 15 '16 at 19:31
  • Right, he should be asserting the tasks, but asserting before you actually know if the tasks are created are a pain since there is usually an issue of seeing the debug logs if the assert fails, but what would mocking do in this case? This wasn't meant to be a solid answer, but more of a starting point to get his tests moving in the right direction – EricSSH Apr 15 '16 at 19:36
  • sorry - OP has a hardcoded ID set for aId; easy to miss – cropredy Apr 15 '16 at 19:38
  • @EricSSH Thanks for the help, I was able to find the issue, it wasn't with this class at all, there was an error in a completely separate class. Thanks again! – AJ47 Apr 15 '16 at 20:38

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.