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
Richard StephensRichard Stephens 

test class for keeping tasks after account owner change

I'm using a great snippet of code created by Jake Backues in the following link: change owner without changing tasks (https://developer.salesforce.com/forums/?id=906F000000091paIAA)

The problem is now testing this.  I'm new at this and have done my best to create a test class.  The problem is, my code coverage is 0%.  Can anyone point me in the right direction on how to get the test class to test the use case?

Trigger:
trigger AccountTrigger on Account (before update, after update) {

    if(Trigger.isBefore) {
        EventUtil.setOwnerIds(Trigger.oldMap, Trigger.newMap);
    }

    if(Trigger.isAfter) {
        EventUtil.updateOwnerIds();
    }
}
Class:
public with sharing class EventUtil {

    /** Event Id => Original Owner Id **/
    public static Map<Id,Id> originalEventOwnerIds = new Map<Id,Id>();

    public static Void setOwnerIds(Map<Id,Account> oldMap, Map<Id,Account> newMap) {

        /** Only process this data if the Account (household) owner changed **/
        Id[] changedAccounts = new Id[]{};
        for(Id hhId : newMap.keySet()) {
            if(oldMap.get(hhId).OwnerId != newMap.get(hhId).OwnerId) {
                changedAccounts.add(hhId);
            }
        }

        for(Event e : [Select Id, WhatId, Subject, OwnerId, Owner.Name from Event where WhatId in :changedAccounts and StartDateTime >= TODAY]) {
            originalEventOwnerIds.put(e.Id, e.OwnerId);
        }
    }

    public static Void updateOwnerIds() {
        
        if(originalEventOwnerIds.isEmpty()) return;

        /** Grab active user list to see if the old user is still active **/
        Map<Id,User> activeUsers = new Map<Id,User>([Select Id, Name from User where IsActive = true and Id in :originalEventOwnerIds.values()]);

        Event[] eventsToUpdate = new Event[]{};
        Event[] allEvents = [Select Id, Subject, OwnerId, Owner.Name from Event where Id in :originalEventOwnerIds.keySet()];
        for(Event e : allEvents) {
            if(originalEventOwnerIds.get(e.Id) != e.OwnerId && activeUsers.keySet().contains(originalEventOwnerIds.get(e.Id))) {
                e.OwnerId = originalEventOwnerIds.get(e.Id);
                eventsToUpdate.add(e);
            }
        }

        if(eventsToUpdate.size() != 0) {
            update eventsToUpdate;
        }
    }
    
}

Test:
@isTest
public class setOwnerTest 
{
    static testMethod void inactiveOwners() 
	{
		Account a = new Account();
			a.Name = 'Test';
        	a.OwnerId = 'testuser';
		insert a;
		
		Contact cont = new Contact();
			cont.FirstName ='test';
			cont.LastName ='Demo';
			cont.accountId = a.id;
		insert cont;
		
        Test.startTest();
			Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator']; 
			User usr = new User(Alias = 'standt', Email='standarduser@testorg.com', 
						EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
						LocaleSidKey='en_US', ProfileId = p.Id, 
						TimeZoneSidKey='America/Los_Angeles', UserName='standarduser@testorg.com');
			insert usr ;
			System.runAs(usr)
			{
				a.ownerId = usr.id;
				update a;
			}
        Test.stopTest();       
    }
}

 
Best Answer chosen by Richard Stephens
Suraj Tripathi 47Suraj Tripathi 47

Hi Richard Stephens,

Please find the solution to your question with 100% Test Coverage.

 I want to tell you that you can get data in trigger.old only when you would update the records. Before insert and after insert there is no data in the trigger.old.

Trigger

trigger AccountTrigger on Account (after update,before update) {
    
      if(Trigger.isBefore && trigger.isUpdate) {
          
        EventUtil.setOwnerIds(Trigger.oldMap, Trigger.newMap);
    }

    if(Trigger.isAfter && trigger.isUpdate) {
        EventUtil.updateOwnerIds();
    }
    }
 
public class EventUtil {

    /** Event Id => Original Owner Id **/
    public static Map<Id,Id> originalEventOwnerIds = new Map<Id,Id>();

    public static Void setOwnerIds(Map<Id,Account> oldMap, Map<Id,Account> newMap) {
 
        /** Only process this data if the Account (household) owner changed **/
        Id[] changedAccounts = new Id[]{};
         for(Id hhId : newMap.keySet()) {
            if(oldMap.get(hhId).OwnerId != newMap.get(hhId).OwnerId) {
                changedAccounts.add(hhId);
            }          
        }
        for(Event e : [Select Id, WhatId, Subject, OwnerId, Owner.Name from Event where WhatId in :changedAccounts and StartDateTime >= TODAY]) {
            originalEventOwnerIds.put(e.Id, e.OwnerId);
        }
        
    }

    public static Void updateOwnerIds() {
        if(originalEventOwnerIds.isEmpty()) return;
        /** Grab active user list to see if the old user is still active **/
        Map<Id,User> activeUsers = new Map<Id,User>([Select Id, Name from User where IsActive = true and Id in :originalEventOwnerIds.values()]);
          Event[] eventsToUpdate = new Event[]{};
        Event[] allEvents = [Select Id, Subject, OwnerId, Owner.Name from Event where Id in :originalEventOwnerIds.keySet()];
        system.debug('originalEventOwnerIds.get(e.Id)::::'+originalEventOwnerIds.get(allEvents[0].Id));
        system.debug(' e.OwnerId::::'+ allEvents[0].OwnerId); 
        for(Event e : allEvents) {
            if(activeUsers.keySet().contains(originalEventOwnerIds.get(e.Id))) {
                e.OwnerId = originalEventOwnerIds.get(e.Id);
                eventsToUpdate.add(e);
             }
        }

        if(eventsToUpdate.size() != 0) {
            update eventsToUpdate;
        }
 
    }
}


Test Class :

@isTest
public class setOwnerTest {
    
    static testMethod void inactiveOwners() 
    {
        try{
            Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator']; 
            User usr = new User(Alias = 'PC', Email='pc@testorg.com',IsActive=true,
                                EmailEncodingKey='UTF-8', LastName='PcTesting', LanguageLocaleKey='en_US', 
                                LocaleSidKey='en_US', ProfileId = p.Id, 
                                TimeZoneSidKey='America/Los_Angeles', UserName='pc@testorg.com');
            insert usr ;
         
            Account a = new Account();
            a.Name = 'Test';
            a.OwnerId=usr.id;
            insert a;
         
            User usrr = new User(Alias = 'pct', Email='pct@testorg.com',IsActive=true, 
                                 EmailEncodingKey='UTF-8', LastName='pcTestingg', LanguageLocaleKey='en_US', 
                                 LocaleSidKey='en_US', ProfileId = p.Id, 
                                 TimeZoneSidKey='America/Los_Angeles', UserName='pct@testorg.com');
            insert usrr ;
               
            Event e = new Event();
            e.WhatId=a.id;
            e.StartDateTime=system.today()+2;
            e.EndDateTime=system.today()+5;
            e.OwnerId=usrr.id;
            insert e;
            Account ac=[select id,name from Account where name='Test' limit 1];
            ac.name='imtiaz';
            ac.OwnerId=usrr.id; 
            update ac;
       
            test.startTest();
            EventUtil.setOwnerIds(oldMap,newMap);
            EventUtil.updateOwnerIds();
            test.stopTest();
        }
        catch(exception e){
            system.debug('Message:: '+e.getMessage());
            system.debug('Line:: '+e.getLineNumber());
            
        }
        
    }
    
}

Please let me know it is working or not??? please tell

If it helps you please mark it as Best Answer so that other people  would take reference from it.

Thank You!

All Answers

ravi soniravi soni
hi Richard,
try following test class
@isTest
public class EventUtilTest {
     static testMethod void inactiveOwners() {
         list<User> lstUser = new list<User>();
         Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator']; 
			User usr = new User(Alias = 'standt', Email='standarduser@testorg.com', 
						EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
						LocaleSidKey='en_US', ProfileId = p.Id, 
						TimeZoneSidKey='America/Los_Angeles', UserName='standtStandarduser@testorg.com');
		lstUser.add(usr);	
         User usr1 = new User(Alias = 'standt1', Email='standarduser54321@testorg.com', 
						EmailEncodingKey='UTF-8', LastName='Testing 2', LanguageLocaleKey='en_US', 
						LocaleSidKey='en_US', ProfileId = p.Id, 
						TimeZoneSidKey='America/Los_Angeles', UserName='Testing2Standarduser54321@testorg.com');
		lstUser.add(usr1);	
         insert lstUser ;
			
                 
		Account a = new Account();
			a.Name = 'Test';
        	a.OwnerId =lstUser[0].Id;
		insert a;
          
        Event oEvent = new Event();
        oEvent.WhatId = a.Id;
         oEvent.StartDateTime = system.TODAY() + 2;
          oEvent.DurationInMinutes = 2;
         oEvent.Subject = 'test';
         oEvent.OwnerId =lstUser[0].Id; 
        insert oEvent;
         System.runAs(usr){
				a.ownerId = lstUser[1].id;
				update a;
			}

         for(Event e : [Select Id, WhatId, Subject, OwnerId, Owner.Name from Event 
                        where WhatId =: a.Id and StartDateTime >= TODAY]) {
                            system.debug('e : ' + e);
                        }
        
		}
}

if it resolve your issue, don't forget to marking it as best.
Thank You
Suraj Tripathi 47Suraj Tripathi 47

Hi Richard Stephens,

Please find the solution to your question with 100% Test Coverage.

 I want to tell you that you can get data in trigger.old only when you would update the records. Before insert and after insert there is no data in the trigger.old.

Trigger

trigger AccountTrigger on Account (after update,before update) {
    
      if(Trigger.isBefore && trigger.isUpdate) {
          
        EventUtil.setOwnerIds(Trigger.oldMap, Trigger.newMap);
    }

    if(Trigger.isAfter && trigger.isUpdate) {
        EventUtil.updateOwnerIds();
    }
    }
 
public class EventUtil {

    /** Event Id => Original Owner Id **/
    public static Map<Id,Id> originalEventOwnerIds = new Map<Id,Id>();

    public static Void setOwnerIds(Map<Id,Account> oldMap, Map<Id,Account> newMap) {
 
        /** Only process this data if the Account (household) owner changed **/
        Id[] changedAccounts = new Id[]{};
         for(Id hhId : newMap.keySet()) {
            if(oldMap.get(hhId).OwnerId != newMap.get(hhId).OwnerId) {
                changedAccounts.add(hhId);
            }          
        }
        for(Event e : [Select Id, WhatId, Subject, OwnerId, Owner.Name from Event where WhatId in :changedAccounts and StartDateTime >= TODAY]) {
            originalEventOwnerIds.put(e.Id, e.OwnerId);
        }
        
    }

    public static Void updateOwnerIds() {
        if(originalEventOwnerIds.isEmpty()) return;
        /** Grab active user list to see if the old user is still active **/
        Map<Id,User> activeUsers = new Map<Id,User>([Select Id, Name from User where IsActive = true and Id in :originalEventOwnerIds.values()]);
          Event[] eventsToUpdate = new Event[]{};
        Event[] allEvents = [Select Id, Subject, OwnerId, Owner.Name from Event where Id in :originalEventOwnerIds.keySet()];
        system.debug('originalEventOwnerIds.get(e.Id)::::'+originalEventOwnerIds.get(allEvents[0].Id));
        system.debug(' e.OwnerId::::'+ allEvents[0].OwnerId); 
        for(Event e : allEvents) {
            if(activeUsers.keySet().contains(originalEventOwnerIds.get(e.Id))) {
                e.OwnerId = originalEventOwnerIds.get(e.Id);
                eventsToUpdate.add(e);
             }
        }

        if(eventsToUpdate.size() != 0) {
            update eventsToUpdate;
        }
 
    }
}


Test Class :

@isTest
public class setOwnerTest {
    
    static testMethod void inactiveOwners() 
    {
        try{
            Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator']; 
            User usr = new User(Alias = 'PC', Email='pc@testorg.com',IsActive=true,
                                EmailEncodingKey='UTF-8', LastName='PcTesting', LanguageLocaleKey='en_US', 
                                LocaleSidKey='en_US', ProfileId = p.Id, 
                                TimeZoneSidKey='America/Los_Angeles', UserName='pc@testorg.com');
            insert usr ;
         
            Account a = new Account();
            a.Name = 'Test';
            a.OwnerId=usr.id;
            insert a;
         
            User usrr = new User(Alias = 'pct', Email='pct@testorg.com',IsActive=true, 
                                 EmailEncodingKey='UTF-8', LastName='pcTestingg', LanguageLocaleKey='en_US', 
                                 LocaleSidKey='en_US', ProfileId = p.Id, 
                                 TimeZoneSidKey='America/Los_Angeles', UserName='pct@testorg.com');
            insert usrr ;
               
            Event e = new Event();
            e.WhatId=a.id;
            e.StartDateTime=system.today()+2;
            e.EndDateTime=system.today()+5;
            e.OwnerId=usrr.id;
            insert e;
            Account ac=[select id,name from Account where name='Test' limit 1];
            ac.name='imtiaz';
            ac.OwnerId=usrr.id; 
            update ac;
       
            test.startTest();
            EventUtil.setOwnerIds(oldMap,newMap);
            EventUtil.updateOwnerIds();
            test.stopTest();
        }
        catch(exception e){
            system.debug('Message:: '+e.getMessage());
            system.debug('Line:: '+e.getLineNumber());
            
        }
        
    }
    
}

Please let me know it is working or not??? please tell

If it helps you please mark it as Best Answer so that other people  would take reference from it.

Thank You!

This was selected as the best answer
Richard StephensRichard Stephens
Thank you! This works!