function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
JGillespieJGillespie 

Test Class for Trigger

My Apex Trigger works properly, but I'm having trouble with my test. Below is by test method:

 

@isTest
private class taskUpdateLeadStatusTests {

static testMethod void validateUpdateLeadStatusWithCall() {

Lead l = new Lead (LastName='Phillips', Company='Phil Inc.');
l.Status = 'Open';
insert l;

Task t = new Task();
t.Subject = 'Call';
t.Status = 'Completed';
t.WhoId = l.Id;
insert t;

System.assertEquals(l.Status, 'Contacted');

}

static testMethod void validateUpdateLeadStatusWithEmail() {

Lead l = new Lead (LastName='Phillips', Company='Phil Inc.');
l.Status = 'Open';
insert l;

Task t = new Task();
t.Subject = 'Email';
t.Status = 'Completed';
t.WhoId = l.Id;
insert t;

System.assertEquals(l.Status, 'Contacted');

}

}

 

 

Here is the trigger associated with the test:

 

trigger taskUpdateLeadStatus on Task (after insert, after update) {

list<lead> liLeads = new list<lead>();
list<id> liIds = new list<id>();

for(Task sTask : trigger.new)
{
if(sTask.Status == 'Completed' && (sTask.Subject == 'Call' || sTask.Subject == 'Email'))
{
liIds.add(sTask.WhoId);
}
}

for(Lead sLead : [select Id, Status from Lead where Id in : liIds])
{
sLead.Status = 'Contacted';
liLeads.add(sLead);
}

update liLeads;

}

 

 

Can someone provide guidance on this topic? 

 

Thanks,

CheyneCheyne

Before you can see the updated data in your lead, you have to query for the lead. In your test, the status in your variable "l" is still equal to "Open," even though the trigger may have executed on that lead. After you insert the task, but before your System.assertEquals call, try querying for the lead with

 

Lead updatedLead = [SELECT Status FROM Lead WHERE Id = :l.Id];

 

Then you can try System.assertEquals(updatedLead.Status, 'Contacted')

JGillespieJGillespie

Thanks! 

 

I'll give it a try and let you know how it goes. 

 

JGillespieJGillespie

So my test was a success and I have 100% code coverage, but my deployment to production failed. It says, 'test coverage of selected Apex Trigger is 0%, at least 1% test coverage is required.' Is there a step I'm missing? 

 

Do I have to deploy my test as well as my Apex Trigger? 

 

Thanks

 

 

CheyneCheyne

Yes, you have to deploy your test class as well.