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
Bharat SBharat S 

Can anyone tell me what is wrong with the test method I have written in the following test class

Trigger is working fine and updating event whenever Title is getting updated on Contact. Just my test method is not covering any line in my apex class when i run the test class. Please help regarding this asap.

Trigger Handler Method in Apex Class for AfterUpdate trigger on Contact


public static void AfterUpdate(List<Contact> conList, Map<Id,Contact> oldContactMap){
        
        Set<Id> UpdatedContactID = new Set<Id>();
        
        for( Contact con : conList)
        {
            if(con.Title!=oldContactMap.get(con.Id).Title){
                UpdatedContactId.add(con.Id);}
                          
        }
     
      //  system.debug('UpdatedContactId*****'+UpdatedContactId);
      
        List<Event> eventList = new List<Event>();
        try
        {
            for(Event e : [SELECT Id,Title__c FROM Event where  StartDateTime > Today and Whoid in : UpdatedContactId])
            {
                eventList.add(e);
                
            }
            
            if(eventList.size()>0){
                update eventList;
            }
            
            //System.debug('eventList' + eventList);
        }
        catch(exception e)
        {
            throw e;    
        }
    }

Test Method in Test Class for above Apex method

  @isTest static void method1() {
        Profile prof = [SELECT Id FROM Profile WHERE Name='System Administrator'];
        User user = new User(firstName = 'test1',lastName = 'test2',profileId = prof.id,
                             username = 'test@test.com'+Math.random(),email = 'test@test.com',
                             Alias = 'ts',TimeZoneSidKey = 'Asia/Kolkata',LocaleSidKey = 'en_US',
                             EmailEncodingKey = 'UTF-8',LanguageLocaleKey = 'en_US');
        insert user;
        
        System.runAs(user){
            
            List<Account>TestDataAccountList=New List<Account>(TestDataUtility.createAccounts(1));
            List<Contact>ContactList=New List<Contact>();       
            Contact Cons = (new Contact(firstname=TestDataUtility.generateRandomString(5),lastname='Test',AccountId=TestDataAccountList[0].Id,MailingPostalCode='999999',
                                        MailingStreet= 'Contact1Steet',MailingState='State45', MailingCountry='TestCountry', Title= TestDataUtility.generateRandomString(5),
                                        MailingCity='City67', isPrimary__c=True));        
            ContactList.add(Cons);
            insert ContactList;   
            
            List<Event> EventListTest = New List<Event>();
            
            Event Eve = new Event(Subject =TestDataUtility.generateRandomString(4) + 'Call', StartDateTime = Date.newInstance(2020, 12, 9),
                                  EndDateTime =Date.newInstance(2020, 12, 9), Location__c = 'Client Office', WhoId = Cons.Id, OwnerId= User.Id);
            
            EventListTest.add(Eve);
            insert EventListTest;
            
            
            Test.startTest();
            
            List<Contact>UpdatedContactList=New List<Contact>();   
            
            Contact Cons1 = (new Contact(firstname=TestDataUtility.generateRandomString(5),lastname='Test',AccountId=TestDataAccountList[0].Id,MailingPostalCode='999999',
                                        MailingStreet= 'Contact1Steet',MailingState='State45', MailingCountry='TestCountry1', Title= 'Title9',
                                        MailingCity='City67', isPrimary__c=True));
            UpdatedContactList.add(Cons1);
            update UpdatedContactList;
            
            List<Event> UpdatedEventListTest = New List<Event>();
            
            Event Eve1 = new Event(Subject =TestDataUtility.generateRandomString(4) + 'Call', StartDateTime = Date.newInstance(2016, 12, 9),
                                  EndDateTime =Date.newInstance(2016, 12, 9), Location__c = 'Client Office', WhoId = Cons1.Id, OwnerId= User.Id);
            UpdatedEventListTest.add(Eve1);
            update UpdatedEventListTest;
            
            Test.stopTest();   
            
        }
    }
Andrew GAndrew G
Its a bit hard to read, but i think the issue is that you have an AfterUpdate Trigger and you are not actually updating the record.  If i'm reading your test class correctly, you seem to be inserting new contacts only, not grabbing the contact that you created and then updating it.

Regards
Andrew
Andrew GAndrew G
Test.startTest();
List<Contact>UpdatedContactList=New List<Contact>();   
UpdatedContactList= [SELECT Id, Title FROM Contact WHERE lastname = 'Test'];

for (Contact con : UpdatedContactList ) {
    con.Title = 'mister';   //data change to test
    UpdatedContactId.add(con.Id);  // build the list of Ids for the event test while we loop
}
update UpdatedContactList;

List<Event> UpdatedEventListTest = New List<Event>();
UpdatedEventListTest = [SELECT Id, Title FROM Event WHERE StartDateTime > Today and Whoid in : UpdatedContactId];
for (Event ev : UpdatedEventListTest ) {
    System.assertEquals('mister',ev.Title);
}

Remember - test classes without asserts are useless.

Regards
Andrew
Maharajan CMaharajan C
Hi Bharat,

Try the below update method:

You need to update the contact title once the contact and Event is inserted.

@isTest static void method1() {
        Profile prof = [SELECT Id FROM Profile WHERE Name='System Administrator'];
        User user = new User(firstName = 'test1',lastName = 'test2',profileId = prof.id,
                             username = 'test@test.com'+Math.random(),email = 'test@test.com',
                             Alias = 'ts',TimeZoneSidKey = 'Asia/Kolkata',LocaleSidKey = 'en_US',
                             EmailEncodingKey = 'UTF-8',LanguageLocaleKey = 'en_US');
        insert user;
        
        System.runAs(user){
            
            List<Account>TestDataAccountList=New List<Account>(TestDataUtility.createAccounts(1));
            Contact Cons = (new Contact(firstname=TestDataUtility.generateRandomString(5),lastname='Test',AccountId=TestDataAccountList[0].Id,MailingPostalCode='999999',
                                        MailingStreet= 'Contact1Steet',MailingState='State45', MailingCountry='TestCountry', Title= TestDataUtility.generateRandomString(5),
                                        MailingCity='City67', isPrimary__c=True));        
            insert Cons;   
            
            
            Event Eve = new Event(Subject =TestDataUtility.generateRandomString(4) + 'Call', StartDateTime = Date.newInstance(2020, 12, 9),
                                  EndDateTime =Date.newInstance(2020, 12, 9), Location__c = 'Client Office', WhoId = Cons.Id, OwnerId= User.Id);
            
            insert Eve;

            Test.startTest();
            Cons.Title = 'Title9';
            update Cons;

            System.assertEquals('Title9',Cons.Title); 
            Test.stopTest();   
            
        }
    }

Thanks,
Maharajan.C
Andrew GAndrew G
@Maharajan

Your assert would be near useless. Your assert checks the in memory value which you updated.

This trigger updates the Event record from the Contact based on the Title field changing.    For the assert to have value, you need to go the record that should be updated by the code/trigger and test that value.

The idea of test code is to check that the code does what you expected it to do.  And that when someone else adds code or processes to the environment, the existing code is not compromised.

Regards
Andrew
 
Bharat SBharat S
@Andrew and @Maharajan thanks for the help. I need one more help.

I have written trigger to update selected Contact's title on event whenever event is geeting inserted. I need to do the same task whenever event is getting updated. My code is working perfectly for after insert trigger.

I am attaching the trigger and triggerhandler class below. Please help creating trigger handler method when event is updated.

Event Trigger:-
 
trigger EventTrigger on Event (before insert, before update, after insert, after update) {
 
    if(Trigger.IsAfter)
    {
        if (Trigger.isInsert) {
            EventTriggerHandler.AfterInsert(trigger.newMap);
        }
        
        if (Trigger.isUpdate) {
            EventTriggerHandler.AfterInsert(trigger.newMap);
        }
    }
    
}

EventTriggerHandler:-

public class EventTriggerHandler {
    
    public static String comma = ',' ;

 public static void AfterInsert(Map<id, Event> EventMap)
    {
        try
        {
            String NameTitle ='';
            String Names;
            
            List<EventRelation>EveRelationList=New List<EventRelation>();
            EveRelationList = [SELECT Id, RelationId,EventId FROM EventRelation WHERE EventId In : eventMap.keyset() and RelationId != null];
            system.debug('AfterInsert count_____'+EveRelationList.size());
            Set<Id> WhoIds = New set<Id>();
            for(EventRelation eveRel : EveRelationList){
                WhoIds.add(eveRel.RelationId);
                system.debug('WhoIds after insert_____'+WhoIds);
            }
            List<Contact> ConList = New List<Contact>();
            ConList=[Select Id,Title,FirstName,LastName, Name FROM Contact WHERE Id In : WhoIds and Title != null and Name != null];
            for(Contact c : ConList){
                if(c.Title!= null)
                {
                    NameTitle = NameTitle+c.Name + '(' + c.Title + ')' + comma ;
                }
            }
            Names = NameTitle.removeEnd(comma);
            System.debug('Names'  + Names);
            List<Event> eventList = new List<Event>();
            
            for (Event e : [select id, Title__c from Event where Id in: eventMap.keyset()])
            {
                e.Title__c = Names;
                eventList.add(e);
            }
            
             if(eventList.size()>0){
                update eventList;
        }
        }
        catch(exception e)
        {
            throw e;    
        }
    }      
 
Bharat SBharat S
Can any of you please help in this asap.
Andrew GAndrew G
The basic logic seems OK.  Where exactly is the issue?

Regards
Andrew