[SalesForce] Trigger not updating field in Test Class

I'm pretty new to Apex and I'm trying to write a trigger that will update my LeadStatus field from 'Open-Not Contacted' to 'Open- Working' upon completion of sent email (logged in Activity History). Basically my Sales team sends out a mass email to their List views and after that first email is logged in Activity History, my LeadStatus field updates which in turns activates my process builder workflow.

I've done deep research and have finally put together a trigger and a test class, but I'm only getting 91% code coverage. The 9% that's failing is the update LeadStatus part which is the only reason I'm doing this.

Trigger

trigger EmailTask on Task (after insert) {
// set up lists
List<Lead> startProcess = new List<Lead>();
Map<Id, Task> taskMap = new Map<Id, Task>();

// go through the list of tasks that were inserted
for (Task t: Trigger.New)
{
  // add the Lead id (whoID) and their values to a map
  if (t.WhoId  != null)
    {
        taskMap.put(t.WhoId, t);
    }
}
// if the map is not empty
if (taskMap.size() > 0)
{
    // get all of the Leads related to the tasks
    startProcess = [SELECT Id, Status FROM Lead WHERE Id IN: taskMap.keySet()];
    // go through the list for each Lead
    for (Lead ld: startProcess)
    { if (ld.Status =='Open- Not Contacted')
        // set the new Lead status
      ld.Status = 'Open- Working';
    }
    update startProcess;

}
}

Test Class

@isTest(seealldata = false)

public class TestClassforTrigger {

static Lead createLead() {
Lead ld = new Lead();
ld.LastName = 'Tulsani';
ld.Company ='ABC Corp';
ld.Status='Open- Not Contacted';
return ld;
}

static Task createTask(Id ldId) {
    Task tk = new Task();
   tk.OwnerId= '005590879000Sx6';
    tk.Subject ='Call for test class';
    tk.WhoId = ldid;
    tk.Priority = 'Normal';
    return tk;
}

static testMethod void TestInsertTask() {
    Test.startTest();
    Lead createlead = createLead();
    insert createlead;
    Lead Getlead = [SELECT Status FROM Lead where ID = : createlead.id];
    Task tk = createTask(createlead.id);

    insert tk;
     Lead Getleadupdated = [SELECT Status FROM Lead where ID = : createlead.id];


    Test.stopTest();
    System.assertEquals('Open- Working', Getleadupdated.Status); 

}
}

Best Answer

The error is in your Status. In the trigger you've got:

if (l.Status =='Open- Not Contacted')

(note the n- N), and in your test class you create it as:

ld.Status='Open -Not Contacted';

(note the n -N). That misplaces whitespace is probably the reason why that line is not getting covered

Edit: Try to use constants for this kind of things. It will make your life easier.

Related Topic