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
newbiewithapexnewbiewithapex 

How do I write test class method to cover If loop?

I am trying cover if loop from EventHandler class but I can't figurer out why this part of the code is not covered. Test class is way too long to post it here so can someone please help me with this?
if(eveRels !=null && eveRels.size()>0){
                  for(EventRelation eveRel : eveRels){
                    if(!test.isRunningTest()) {
                        if(eveRel.Relation.type.equals('User')){
                            userRecptList.add(eveRel.RelationId);
                        }
                        if(eveRel.Relation.type.equals('Lead')){
                            leadRecptList.add(eveRel.RelationId);
                        }
                        if(eveRel.Relation.type.equals('Contact')){
                            contactRecptList.add(eveRel.RelationId);
                        }
                    }
                    else {
                        if(string.valueOf(eveRel.RelationId).startswith(User.SObjectType.getdescribe().getKeyPrefix())){
                            userRecptList.add(eveRel.RelationId);
                        }
                        if(string.valueOf(eveRel.RelationId).startswith(Lead.SObjectType.getdescribe().getKeyPrefix())){
                            leadRecptList.add(eveRel.RelationId);
                        }
                        if(string.valueOf(eveRel.RelationId).startswith(Contact.SObjectType.getdescribe().getKeyPrefix())){
                            contactRecptList.add(eveRel.RelationId);
                        }
                    }
                }
                }

 
Raj VakatiRaj Vakati
Give me complete class ?
newbiewithapexnewbiewithapex
@isTest
private class EventHandler_Test {
    private static List < sObject > listSFIds = Test.loadData(SalesforceIds__c.sObjectType, 'salesforceIds');
    private static List < sObject > lsConstants = Test.loadData(CS_UtilConstants__c.sObjectType, 'customSettingData');
    private static List < Event > Eventlist = new List < Event > ();
    private static User tmUser = new User();
    private static User scUser = new User();
    private static User thisUser = [select Id from User where Id = : UserInfo.getUserId() limit 1];
    private static Account testAccount = new Account();
    private static Account testAccount1 = new Account();
    private static Account testAccount2 = new Account();
    private static Opportunity testOppty = new Opportunity();
    private static Opportunity testOppty2 = new Opportunity();
    private static contact testContact = new Contact();
    private static contact testContact2 = new Contact();
    private static Lead testLead = new Lead(FirstName='Testdata', LastName='Lead', Company='Abc');
    private static String rDaily = 'RecursDaily';
    private static Agenda_Item__c testAgendat1 = new Agenda_Item__c();
    private static RPM__c testRPM1 = new RPM__c();
    private static Id profileId;
    private static User usrDsm1 = new User();
    private static User usrDsm2 = new User();
    
    /**
     * Method to create test Users, Accounts and Events 
     * @name createTestData
     * @param String
     * @return void
     */
    static void createTestData(String statusString) {
        tmUser = UTIL_TestDataCreation.createUser('tmtst', SalesforceIds__c.getOrgDefaults().Profile_USF_TerritoryManager__c);
        Database.insert(tmUser, true);
        testAccount = UTIL_TestDataCreation.createSingleAccount('TestAccount', tmUser.Id);
        
        testAccount.Account_Status__c = statusString;
        Database.insert(testAccount, true);
        testContact = UTIL_TestDataCreation.createContact('test contact', 'cont', true);
        Database.insert(testContact, true);
        
        testContact2 = UTIL_TestDataCreation.createContact('test contact', 'cont', true);
        Database.insert(testContact2, true);

        testOppty = UTIL_TestDataCreation.createOpportunity('TestOppty', SalesforceIds__c.getOrgDefaults().RecordType_Prospect_Locally_Managed__c, testAccount.Id);
        Database.insert(testOppty, true);
        testOppty2 = UTIL_TestDataCreation.createOpportunity('TestOppty2', SalesforceIds__c.getOrgDefaults().RecordType_Prospect_Locally_Managed__c, testAccount.Id);
        Database.insert(testOppty2, true);
        
    }

    /**
     * Method to create test Users, Accounts and Events
     * @name createTestDataforSCEvent
     * @param NA
     * @return void
     */
    static void createTestDataforSCEvent() {
        /*Insert TM User, Opportunity and Account */
        scUser = UTIL_TestDataCreation.createUser('sctst', SalesforceIds__c.getOrgDefaults().Profile_USF_SalesCoordinator__c);
        Database.insert(scUser, true);
        tmUser = UTIL_TestDataCreation.createUser('tmtst', SalesforceIds__c.getOrgDefaults().Profile_USF_TerritoryManager__c);
        tmUser.Sales_Coordinator__c = scUser.Id;
        Database.insert(tmUser, true);
        testAccount1 = UTIL_TestDataCreation.createSingleAccount('TestAccount', tmUser.Id);
        testAccount1.Account_Status__c = 'Prospect';
        Database.insert(testAccount1, true);
        testAccount2 = UTIL_TestDataCreation.createSingleAccount('TestAccount2', tmUser.Id);
        testAccount2.Account_Status__c = 'Active';
        Database.insert(testAccount2, true);
        
        testContact = UTIL_TestDataCreation.createContact('test contact', 'cont', true);
        Database.insert(testContact, true);
        Database.insert(testLead, true);
    }

    /**
     * Method to test addInvitee(), getAccountStatus(), PopulateAccount() and CalendarDay update functions in event handler when whatId is Account
     * @name testAccountEvent
     * @param NA
     * @return void
     */
    static testmethod void testAccountEvent() {
        test.startTest();
        /*Insert TM User, SC User and Account */
        createTestData('Prospect');
        Event testEvent = UTIL_TestDataCreation.createSingleEvent(system.now(), tmUser.Id, testAccount.Id);
        testEvent.WhoID= testContact.Id; 
        testEvent.Description='TestEvent';
        /*Test update of Acct_Oppty_Type__c and owner of Account on insert*/
        test.startTest();
        system.runAs(tmUser) {
            Database.insert(testEvent, true);
        }
        test.stopTest();
        
        /*verify the results*/
        Event result = [select id, Account_Name__c, Acct_Oppty_Type__c, Account_Id__c,WhoID,Description from Event where Id = : testEvent.Id limit 1];
        system.assertEquals(result.Acct_Oppty_Type__c, 'Prospect');
        system.assertEquals(result.Account_Id__c, testAccount.Id);
        system.assertEquals(result.Account_Name__c, testAccount.Name);
        /*Test update of Acct_Oppty_Type and Calendar Day on update of Event*/
        testAccount.Account_Status__c = 'ABCD';
        
        Database.update(testAccount, true);
        testEvent.StartDateTime = system.now() + 10;
        testEvent.EndDateTime = testEvent.StartDateTime + (10 / 24.0);
        testEvent.whoId = testContact2.Id;
        Database.update(testEvent, true);
        /*verify the results*/
        result = [select id, Acct_Oppty_Type__c from Event where Id = : testEvent.Id limit 1];
        //result.IsRecurrence=True;
        Database.update(testEvent, true);
        //system.assertEquals(result.Acct_Oppty_Type__c, 'Existing Account');
    }

    /**
     * Method to test getAccountStatus(), PopulateAccount() and CalendarDay update functions in event handler when whatID is Opportunity
     * @name testOpportunityEvent
     * @param NA
     * @return void
     */
    static testmethod void testOpportunityEvent() {
        /*Insert TM User, Opportunity and Account */
        createTestData('Prospect');
        Event testEvent = UTIL_TestDataCreation.createSingleEvent(system.now(), tmUser.Id, testOppty.Id);
        /*Test update of Acct_Oppty_Type__c, Account fields and Calendar Day*/
        testEvent.Description = 'Abcd';  
        testEvent.WhoID= testContact.Id; 
        List<string> strList= new List<string>();
        strList.add(string.valueOf(testEvent.WhoID));
        strList.add(string.valueOf(testContact2.Id));
        test.startTest();
        system.runAs(thisUser) {
            Database.insert(testEvent, true);
        }
        System.debug('******testEvent'+testEvent);
        List<EventRelation> evRel = UTIL_TestDataCreation.addEventInvitees(string.valueOf(testEvent.Id), strList);
        upsert evRel;
        system.debug('evRel ' +evRel );
         List<EventRelation> eveRels2 = [SELECT Id, RelationId, Relation.Name, Relation.type, Response, Status, RespondedDate, eventId
           FROM EventRelation Where Id =: evRel[0].ID
           ];
           System.debug('testclasseveRelsold' + eveRels2);
                                   
        test.stopTest();
        /*verify the results*/
        Event result = [select id, Account_Name__c,WhatId,Description, Acct_Oppty_Type__c, Account_Id__c
        from Event where Id = : testEvent.Id limit 1];
        result.WhatId = testOppty2.Id;
        result.Description = 'testteststststst';
        Database.update(result,true);
        
        system.assertEquals(result.Acct_Oppty_Type__c, 'Prospect');
        system.assertEquals(result.Account_Id__c, testAccount.Id);
        system.assertEquals(result.Account_Name__c, testAccount.Name);
        testAccount.Account_Status__c = 'ABCD';
        Database.update(testAccount, true);
        testEvent.StartDateTime = system.now() + 5;
        testEvent.EndDateTime = testEvent.StartDateTime + (1 / 24.0);
        testEvent.Automatically_Extend_Recurring_Event__c = true;
        /*Test update of Acct_Oppty_Type and calendar Day when Event is updated*/
        system.debug('testEvent' + testEvent);
       
        Database.update(testEvent, true);
         List<EventRelation> eveRels = [SELECT Id, RelationId, Relation.Name, Relation.type, Response, Status, RespondedDate, eventId
                                       FROM EventRelation
                                       ];
                                       System.debug('testclasseveRels' + eveRels);
                                       
           List<EventRelation> eveRels1 = [SELECT Id, RelationId, Relation.Name, Relation.type, Response, Status, RespondedDate, eventId
           FROM EventRelation Where Id =: evRel[0].ID
           ];
           
          //system.assert(false,'testclasseveRelsNew' + eveRels1);
           System.debug('testclasseveRelsNew' + eveRels1);
                                       
        /*verify the results*/
        result = [select id, Acct_Oppty_Type__c from Event limit 1];
        //system.assertEquals(result.Acct_Oppty_Type__c, 'Existing Account');
        // delete result;
    }

    /**
     * Method to test update of AccountStatus when the value is null.
     * @name testNullStatusEvent
     * @param NA
     * @return void
     */
    static testmethod void testNullStatusEvent() {
        /*Insert TM User, Opportunity and Account */
        createTestData(null);
        Event testEvent1 = UTIL_TestDataCreation.createSingleEvent(system.now(), tmUser.Id, testOppty.Id);
        testEvent1.Description='TestEvent1';
        Event testEvent2 = UTIL_TestDataCreation.createSingleEvent(system.now(), tmUser.Id, testAccount.Id);
        testEvent2.Description='TestEvent2';
        /*Test update of Acct_Oppty_Type__c, Account fields and Calendar Day*/
        test.startTest();
        system.runAs(thisUser) {
            Database.insert(testEvent1, true);
            Database.insert(testEvent2, true);
        }
        test.stopTest();
        /*verify the results*/
        Event result1 = [select id, Account_Name__c, Acct_Oppty_Type__c, Account_Id__c,Description
        from Event where Id = : testEvent1.Id limit 1];
        Event result2 = [select id, Account_Name__c, Acct_Oppty_Type__c, Account_Id__c,Description
        from Event where Id = : testEvent2.Id limit 1];
        system.assertEquals(result1.Acct_Oppty_Type__c, null);
        system.assertEquals(result2.Acct_Oppty_Type__c, null);
    }

    /**
     *Method to test addInvitee() 
     *@name testChangeOwner
     *@param NA
     *@return NA
     */
    static testMethod void testChangeOwner() {
        /*Insert TM User, SC User and Account */
        createTestDataforSCEvent();
        opportunity opp = new opportunity();
        opp.Name='test opp';
        opp.AccountId = testAccount2.Id;
        opp.StageName = 'Prospect';
        opp.CloseDate = system.today();
        insert opp;
        Event testEvent = UTIL_TestDataCreation.createSingleEvent(system.now(), tmUser.Id, null);
        testEvent.SC_Responsible__c = true;
        testEvent.Description='testEvent';
        testEvent.WhatId = opp.Id;
        /*Test update of Acct_Oppty_Type__c and owner of Account on insert*/
        test.startTest();
        Database.insert(testEvent, true);
        testEvent.SC_Responsible__c = false;
        update testEvent;
        testEvent.SC_Responsible__c = true;
        testEvent.WhatId = testAccount2.Id;
        Database.update(testEvent, true);
        testEvent.SC_Responsible__c = false;
        testEvent.WhatId = testAccount2.Id;
        Database.update(testEvent, true);
        test.stopTest();
        /*verify the results*/
        Event result = [select Id, ownerId from Event where id = : testEvent.Id limit 1];
        System.debug('EVENT CBR =====================>'+result.CBR__c);
        //system.assertEquals(result.ownerId, scUser.Id, 'Owner:' + result.ownerId + ',SC : ' + scUser.Id);
    }

    /**
     *Method to test update Operation on Event trigger
     *@name testUpdateOperation
     *@param NA
     *@return NA
     */
    static testMethod void testUpdateOperation() {
        /*Insert TM User, Opportunity and Account */
        createTestDataforSCEvent();
        Event testEvent1 = UTIL_TestDataCreation.createSingleEvent(system.now(), tmUser.Id, testAccount.Id);
        testEvent1.Description='';
        testEvent1.whoId=testContact.id;
        Eventlist.add(testEvent1);
        Event testEvent2 = UTIL_TestDataCreation.createSingleEvent(system.now(), tmUser.Id, testAccount.Id);
        testEvent2.Description='';
        testEvent2.whoId=testContact.id;
        testEvent2.IsAllDayEvent= true;
        Eventlist.add(testEvent2);
        Database.insert(Eventlist, true);
        //Database.insert(testEvent1,true);
        /*test null on update operation when what ID is null*/
        Business_Review__c testBR = UTIL_TestDataCreation.createBusinessReview('Draft', 'test');
        insert testBR;
        Eventlist[0].whatID = testBR.Id;
        Eventlist[0].Description='asggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg';
        Eventlist[0].SC_Responsible__c = true;
        EventList[0].whoId = testContact2.id;
        Database.update(Eventlist[0], true);
        /*verify the results*/
        Event result1 = [select id, Account_Name__c, Account_Id__c from Event where Id = : Eventlist[0].Id limit 1];
        system.assertEquals(result1.Account_Id__c, null);
        /*test update operation when what ID is changed*/
        testEvent1.WhatId = testAccount2.Id;
        
        Database.update(testEvent1, true);
        result1 = [select id, Account_Name__c, Account_Id__c from Event where Id = : Eventlist[0].Id limit 1];
        system.assertEquals(result1.Account_Id__c, testAccount2.Id);
        Eventlist[0].whoId = testContact.Id;
        Database.update(testEvent1, true);
        
        test.startTest();
        
        
        //Using handler object to cover lines that could not e covered by any testmethod scenario
        EventHandler evnthandlerobj = new EventHandler();
        evnthandlerobj.updateNewComment(Eventlist);
        EventHandler.getTimes (null, null, null, false);
        Event testEvt = UTIL_TestDataCreation.createSingleEvent(system.now(), tmUser.Id, null);
        testEvt.Description='testEvt';
        testEvt.whoId=testContact.id;
        Event testEvt1 = UTIL_TestDataCreation.createSingleEvent(system.now(), tmUser.Id, null);
        testEvt1.Description='testEvt1';
        testEvt1.whoId=testContact.id;
        testEvt1.IsAllDayEvent =true;
        
        List<Event> Evtlist = new List<Event>();
        Evtlist.add(testEvt);
        Evtlist.add(testEvt1);
        Database.insert(Evtlist, true);
        evnthandlerobj.populateAccount(Evtlist);
        evnthandlerobj.sendEmailPreEventCancel(Eventlist[1]);
        evnthandlerobj.sendEmail(new List<Id> {testLead.Id}, new List<Id> {tmUser.Id}, new List<Id> {testContact.Id}, Eventlist[0], true);
        evnthandlerobj.sendEmail(new List<Id> {testLead.Id}, new List<Id> {tmUser.Id}, new List<Id> {testContact.Id}, Eventlist[0], false);
        evnthandlerobj.sendEmail(new List<Id> {testLead.Id}, new List<Id> {tmUser.Id}, new List<Id> {testContact.Id}, Eventlist[1], true);
        evnthandlerobj.sendEmail(new List<Id> {testLead.Id}, new List<Id> {tmUser.Id}, new List<Id> {testContact.Id}, Eventlist[1], false);
        evnthandlerobj.preventCBREventDeletion(Eventlist);
        
        evnthandlerobj.updateOwnertoSC(Eventlist);
        
        Map<Id,Event> testMap = new Map<Id,Event>();
        testMap.put(Eventlist[0].id,Eventlist[0]);
        testMap.put(Eventlist[0].id,Eventlist[0]);
        testMap.put(Eventlist[0].id,Eventlist[0]);
        testMap.put(Eventlist[1].id,Eventlist[1]);
        testMap.put(Eventlist[1].id,Eventlist[1]);
        testMap.put(Eventlist[1].id,Eventlist[1]);
        testMap.put(Eventlist[2].id,Eventlist[2]);
        testMap.put(Eventlist[0].id,Eventlist[0]);
        testMap.put(Eventlist[1].id,Eventlist[1]);
        Evtlist.add(testEvt1);
        Evtlist.add(testEvt1);
        evnthandlerobj.updateAttendeesOnRecurringEventUpdate(Eventlist,testMap);
        test.stopTest();
    }
    
      /**
     *Method to test update Operation on Event trigger
     *@name testNagative
     *@param NA
     *@return NA
     */
    static testMethod void testNagative() {
    createTestDataforSCEvent();
    try{
         Event testEvent1 = UTIL_TestDataCreation.createRecurringEvent(System.now()-2,thisUser.Id,testAccount.Id,rDaily,1,Date.Today()-1,null);
         Database.insert(testEvent1);
           Event testEvent4 =[select Id,WhatId from Event where Id = : testEvent1.Id]; 
           testEvent4.WhatId = null;
           Database.update(testEvent4); 
        }
        catch(Exception e){
        }
    try {
    
       Event testEvent2 = UTIL_TestDataCreation.createRecurringEvent(System.now()-2,thisUser.Id,testAccount.Id,rDaily,1,Date.Today(),null);
       testEvent2.Automatically_Extend_Recurring_Event__c = false;
       Database.insert(testEvent2);
       
        Event testEvent3  = [select Id,RecurrenceEndDateOnly,Automatically_Extend_Recurring_Event__c from Event where Id = : testEvent2.Id];
        testEvent3.RecurrenceEndDateOnly = Date.Today()-1;
        testEvent3.Automatically_Extend_Recurring_Event__c = true;
        Database.update(testEvent3);
        }
        catch(Exception e){
        }
    }
    
     /**
     *Method to test update Operation on Event trigger
     *@name testNagative2
     *@param NA
     *@return NA
     */
    static testMethod void testNagative2() {
      createTestDataforSCEvent();
      Event testEvent1 = UTIL_TestDataCreation.createSingleEvent(system.now(), tmUser.Id, testAccount.Id);
      testEvent1.WhatId = null;
      Database.insert(testEvent1);
       Event testEvent2 = [Select Id,WhatId from Event where Id =:testEvent1.Id];
       testEvent2.WhatId = null;
       update testEvent2;
      
    }
    
     /**
     *Method to Create RPM / Agenda Record data
     *@name createTestDataAgendaRPM
     *@param NA
     *@return NA
     */
        static void createTestDataAgendaRPM() 
        {
            
 			testRPM1 = UTIL_TestDataCreation.createRpm('',System.today());
		 	Database.insert(testRPM1);
		
		 	List<RPM__c> rpmList =  [Select Id From RPM__c ];
		 	
	 	 	testAgendat1 = UTIL_TestDataCreation.creatAgenda(rpmList[0].Id,'Test Agenda');
	 	 	Database.insert(testAgendat1);
            
        }
        
     /**
     *Method to test inserting Agenda event to it parent RPM Record 
     *@name testAgendaEvent
     *@param NA
     *@return NA
     */
    static testMethod void testAgendaEvent() 
    {
 		test.startTest();
 		
 			createTestDataAgendaRPM();
            
			List<Agenda_Item__c> agendaList =  [Select Id From Agenda_Item__c ];
            
            
        	Event ev = new Event(Subject='Email',StartDateTime=system.now(), EndDateTime=system.now()+1, ActivityDate=system.today(), Type = 'Visit - Presentation');
            	ev.whatID = agendaList[0].id;
            	Database.insert(ev);    

        test.stopTest();
        

    }
    
    static testmethod void testEmailPost(){
        Event testEvent = [SELECT Id from Event Where Id != null Limit 1];
        List<string> strList= new List<string>();
        strList.add(string.valueOf(testEvent.WhoID));
        strList.add(string.valueOf(testContact2.Id));
        List<EventRelation> evRel = UTIL_TestDataCreation.addEventInvitees(string.valueOf(testEvent.Id), strList);
        upsert evRel;
        
        EventHandler testClass = new EventHandler();
        test.startTest();
        testClass.sendEmailPostEventUpdate(testEvent);
        test.stopTest();
    }
    
    static testmethod void updateOwnertoSC() {
        List<Event> testList = [SELECT Id from Event Where Id != null Limit 30];
        List<Event> duplicatesTest = new List<Event>();
        Map<Id,Event> testMap = new Map<Id,Event>();
        Event testEvent = testList[0];
        List<string> strList= new List<string>();
        strList.add(string.valueOf(testEvent.WhoID));
        strList.add(string.valueOf(testContact2.Id));
        List<EventRelation> evRel = UTIL_TestDataCreation.addEventInvitees(string.valueOf(testEvent.Id), strList);
        upsert evRel;
        duplicatesTest.add(testEvent);
        duplicatesTest.add(testList[0]);
        duplicatesTest.add(testList[0]);
        /*duplicatesTest.add(testList[1]);
        duplicatesTest.add(testList[1]);
        duplicatesTest.add(testList[2]);
        duplicatesTest.add(testList[2]);*/
        	test.startTest();
        	createTestData('prospect');
        	EventHandler testClass = new EventHandler();
       		testClass.updateAccountOwner(testList);
        testclass.updateAccountOwner(null);
        //testclass.updateAttendeesOnRecurringEventUpdate(testlist,testMap);
        EventRelation testRelation = new EventRelation();
       /* testClass.sendEmailPostEventUpdate(testEvent);
        	testClass.sendEmailPostEventUpdate(testList[0]);
        testClass.sendEmailPostEventUpdate(testList[1]);
        testClass.sendEmailPostEventUpdate(testList[2]);
        testClass.sendEmailPostEventUpdate(testList[3]);
        testClass.sendEmailPostEventUpdate(testList[4]);
*/
        testClass.updateAttendees(duplicatesTest);
        	//testClass.updateOwnertoSC(testList);
        	//createTestDataforSCEvent();
        	test.stopTest();
    }
    
}