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
Deepak ChouhanDeepak Chouhan 

create event using apex for test trigger

Hi,
I have create after trigger for event and i want to write a test method for test trigger but trigger code coverage is 0%. i have test this code into execyte anonymous block but lead is crated but event not. please help me out.

@isTest
private class TestEventTrigger {
    static testMethod void eventTestMethod() {
        lead l = new lead();
        event e = new event();
        List<Id> leadIds=new List<Id>();
        
        l.Rep__c='Vivek Jain';
        l.LastName='Method';
        l.Company='Test';
        l.Status='Open';
        l.Webinar_Status__c='Missed';
        l.Webinar_Status_Value__c=decimal.valueOf('2');
        l.Start_Date__c=datetime.now();
        l.End_Date__c=datetime.now();
        insert l;
        
        
        e.WhatId=l.Id;
        e.OwnerId='00590000001Q5ViAAK';
        e.G2W4SF__Webinar_Status__c='Missing';
        e.G2W4SF__G2W_Attendance_Minutes__c=decimal.valueOf('2');
        e.StartDateTime=datetime.now();
        e.EndDateTime=datetime.now();
        insert e;
        
        
        leadIds.add(e.WhoId);
        List<Lead> leadUpdate=[SELECT End_Date__c,Id,Start_Date__c,Webinar_Status_Value__c,Webinar_Status__c FROM Lead WHERE Id IN :leadIds AND IsConverted=FALSE];
        
        for(Lead lds:leadUpdate){
            lds.Webinar_Status_Value__c=e.G2W4SF__G2W_Attendance_Minutes__c;
            lds.Webinar_Status__c=e.G2W4SF__Webinar_Status__c;
            lds.Start_Date__c=e.StartDateTime;
            lds.End_Date__c=e.EndDateTime;
        }
        try{            
            update leadUpdate;
        }catch(DMLException e){
            system.debug('Leads were not all properly updated.  Error: '+e);
        }
        
        
    }
}
 
StephenKennyStephenKenny
Hi Deepak

This line:  leadIds.add(e.WhoId); is the problem as the WhoId is not know at this point. After you insert the event, you need to query it to return the whoId. From there, you should get coverage.

Something like this:
Event newEvent = [Select id, WhoId from event where id=:l.id] limit 1;
leadIds.add(newEvent.WhoId);

Please remember to mark this thread as solved with the answer that best helps you.

Regards
Stephen