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
RobBirdRobBird 

Test for Apex Trigger

So when I created the triggers in my Sandbox and tested them, I received 72% code coverage. Here is the code (bold is what was not covered by tesing):

 

trigger CopyLeadInformation on Task (before insert, before update) {

list<id> WhoIds = new list<id>();
for (Task t : trigger.new)
    WhoIds.add(t.WhoId);

list<Lead> leadList = [select id,Email from Lead where id in :WhoIds];
map<id, Lead> leadMap = new map<id, Lead>();

for(Lead l : leadList)
    leadMap.put(l.id, l);
   
for (Task tsk : trigger.new){
    if (leadMap.containsKey(tsk.Whoid)){
        Lead l = leadMap.get(tsk.Whoid);
            
        tsk.Email_1__c = l.Email;
        }   
    }
}

 

How do I test the rest to obtain at least 75% coverage?

 

Any help would be appreciated!

Best Answer chosen by Admin (Salesforce Developers) 
RobBirdRobBird

Actually, I think I have it. I tried the code below and came up with 100% coverage:

 

@isTest 
private class CopyLeadInformation {

static testMethod void myTest() {
Lead lead = new Lead();
lead.Email = 'test@test.com';
lead.Account_Number__c = '1234567890';
lead.lastname = 'Testerson';
lead.Company = 'Market Services';
insert lead;

Task task = new Task();
task.WhoId = lead.id;

insert task;
}
}

 

Thank you for pointing me in the right direction!!

All Answers

_Prasu__Prasu_
static testMethod void myTest() {
Lead lead = new Lead();
lead.Email = 'test@test.com';
lead.Name = 'xyz';

insert lead;

Task task = new Task();
task.WhoId = lead.id;

insert task;

}

 

RobBirdRobBird

When I try that, I get: Compile Error: unexpected token: 'testMethod' at line 1 column 7. I know I am doing something wrong here. Any help is greatly appreciated.

RobBirdRobBird

Actually, I think I have it. I tried the code below and came up with 100% coverage:

 

@isTest 
private class CopyLeadInformation {

static testMethod void myTest() {
Lead lead = new Lead();
lead.Email = 'test@test.com';
lead.Account_Number__c = '1234567890';
lead.lastname = 'Testerson';
lead.Company = 'Market Services';
insert lead;

Task task = new Task();
task.WhoId = lead.id;

insert task;
}
}

 

Thank you for pointing me in the right direction!!

This was selected as the best answer