+ Start a Discussion
CNMCNM 

Test Code - AfterInsert Event with Attachment

Hello all, 

I have been trying to test an Event trigger but I'm kind of lost in a particular part of the execution that I want and need to test.
On the Event object I have a Boolean custom field, has_Attachment__c. So if you insert an attachment in an event this Boolean field will be set to true. How do I test this?  
I use a centralize object initialization class: 
 
public with sharing class EventCentralizeObjectInitialization {
	
	
	 public static List<Event> InitTestInsertEvents(Integer count)
     {
     	
     	Account account = new Account(Name ='testEventAfterInsertAccount'); 
    	insert account; 
    	
    	Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator']; 
        User u = new User(Alias = 'systemAd',
                          Email='systemAd@testorg.com', 
       					  EmailEncodingKey='UTF-8', 
       					  LastName='Testing', 
       					  LanguageLocaleKey='en_US', 
            			          LocaleSidKey='en_US', 
            			          ProfileId = p.Id, 
            			          TimeZoneSidKey='America/Los_Angeles', 
            			          UserName='systemAdEvent@testorg.com');
    	
    	insert u; 
    	
    	DateTime dt = System.now(); 
    	
    		List<Attachment> eventAttMap = new List<Attachment>();
     		Blob bodyBlob=Blob.valueOf('Unit Test Attachment Body');
     		
     		List<Event> eventList = new List<Event>(); 
     		    		    		        	        	
        	for(Integer x=0; x< count; x++)
        	{
        		eventList.add(new Event(OwnerId = u.Id,
        		                  Subject ='The test subject',
        				  StartDateTime= dt.addMinutes(-120),
        				  EndDateTime = dt,
        				  WhatId = account.id,
        				  Activity_Type__c = 'Inspection')); 
        	}
        	
        	        		
        	return eventList;	
    
       }
         
 }

Then I pull the method InitTestInsertEvents to my test class like this: 
 
@isTest
private class TestEventAfterInsert {

    public static testMethod void testPrepareEventAfterInsert()
    {
    		 
    	List<Event> eventList = EventCentralizeObjectInitialization.InitTestInsertEvents(2); 
    	List<Attachment> attList = new List<Attachment>();
    	List<FeedItem> feedList = new List<FeedItem>();
    	List<Event> eventToUpdate = new List<Event>();
    	Set<Id> ownerIds = new Set<Id>();
    	Set<Id> accountIds = new Set<Id>();
    	Set<Id> eventAttIds = new Set<Id>(); 
    	Id eventID;
    	
    	
    	Blob bodyBlob=Blob.valueOf('Unit Test Attachment Body');
    	
    	
    	Test.StartTest();  
    	insert eventList;
    	Test.StopTest(); 
    	
    	Map<Id, Event> eventmap = new Map<Id, Event>(eventList);
    	List<Event> events = [SELECT Id, OwnerId, Account.Id, has_Attachment__c, (SELECT Id FROM Attachments) FROM Event WHERE Id IN :eventmap.keySet()]; 	
    	
    	System.assertEquals(events.size(), 2); 
     
     	for(Event e: events)
     	{
     		if(e.Id!=null){
     			attList.add(new Attachment(
     			Name='The test attachment',
     			Body=bodyBlob,
     			ParentId= e.id,
     			OwnerId = e.OwnerId));
     			    			
     		}
     		
     	System.assertNotEquals(attList.size(), 0); 
     	
     	   	
     	}
     	
     	if(!attList.isEmpty() && attList.size()>0)
     	{
     		insert attList; 
       	}
     
     	for(Attachment a: attList)
     	{
     		if(!attList.isEmpty())
     		{
     			Id eventIdAtt = a.ParentId;
     			eventAttIds.add(eventIdAtt);				
     			}
     		}
     		
     	List<Event> eventListAttIds = [SELECT Id, OwnerId, Account.Id, has_Attachment__c FROM Event WHERE Id IN: eventAttIds];	
     	
     		for(Event e: eventListAttIds)
     		{
     			if(!eventListAttIds.isEmpty() && eventListAttIds.size()>0)
     			{
     				e.has_Attachment__c = true;
     				ownerIds.add(e.OwnerId);
     				accountIds.add(e.Account.Id);
     				eventId = e.Id;
     				eventToUpdate.add(e);
     				
     				System.assertEquals(e.has_Attachment__c, true); 
     			}
     		}update eventToUpdate;
     		
     
  }	
}

If I run the test class I only get 47% of the test coverage.
I have been trying different things without getting that percentage higher than 47 :( 

So the question is, how can I pass the events to the test class with an attachment if I can't insert the attachments becasue the ParendIt is not present? Anyone knows how to tests this particular scenario?
Thanks. 
 
MJ Kahn / OpFocusMJ Kahn / OpFocus
First, if you don't show us the code that you're testing, we can't see why your test isn't coverying more than 47% of it. :)

Second, you should put @IsTest in front of your EventCentralizeObjectInitialization class. That code is part of your unit test infrastructure, and doesn't need to be covered by its own unit tests, so flag it with @IsTest.
CNMCNM
Hello MJ. 
The event trigger calls two classes, the EventAfterInsertClass, and the EventAfterUpdateClass.
Here is the code for the EventAfterInsertClass: 
public class EventAfterInsertClass {
   
              
    public static void eventAfterInsert()
    {
        
        List<Event> eventList = new List<Event>();
        List<FeedItem> feedList = new List<FeedItem>();
        List<Event> eventToUpdate = new List<Event>(); 
        Set<Id> ownerIds = new Set<Id>();   
        Set<Id> accountIds = new Set<Id>(); 
        Id eventID;
        
    for(Event e : (List<Event>) trigger.new)
    {
        
     if(e.WhatId !=null && e.WhatId.getSObjectType() == Account.SObjectType)
     {
        eventList.add(e); 
     }
   }
   
    Map<Id,Event> eventAttMap = new Map<Id, Event>([SELECT id, OwnerId, Account.Id, has_Attachment__c, (SELECT Id FROM Attachments) FROM Event WHERE Id IN : eventList]); 
   
   for(Event currentEvent :eventAttMap.values())
    {
                   
        for(Attachment a :currentEvent.Attachments)
        {
                      
           if(currentEvent.Attachments != null && currentEvent.has_Attachment__c== false)
             {
                currentEvent.has_Attachment__c = true; 
                ownerIds.add(currentEvent.OwnerId);
                accountIds.add(currentEvent.Account.Id);
                eventId = currentEvent.id; 
                eventToUpdate.add(currentEvent);
             }
        }   
    }update eventToUpdate; 
    
    
    
    List<EntitySubscription> entityListAccount = [SELECT Id, ParentId, SubscriberId FROM EntitySubscription WHERE ParentId IN: accountIds]; 
    List<EntitySubscription> entityListOwners = [SELECT Id, ParentId, SubscriberId FROM EntitySubscription WHERE ParentID IN: ownerIds];
    
    
    
    /******************************************************
    *         Iteration for Event's Account followers     *
    ******************************************************/
    
           
    for(EntitySubscription entityAccount : entityListAccount)
    {
    
    if(!entityListAccount.isEmpty() && entityListAccount.size() >0)
    {
            
            FeedItem accountFeedItem = new FeedItem(
            ParentId = entityAccount.SubscriberId,
            Body = 'This is the msg',
            LinkUrl = 'https://eu5.salesforce.com/'+ eventId);
            
            feedList.add(accountFeedItem);
    
        }
        
    }
    
    
    
    /******************************************************
    *         Iteration for Event's Owner followers       *
    ******************************************************/
    
    
    for(EntitySubscription entityOwners : entityListOwners)
    {
    
    if(!entityListOwners.isEmpty() && entityListOwners.size()>0)
    {
        
           FeedItem accountFeedItem = new FeedItem(
           ParentId = entityOwners.SubscriberId,
           Body = 'This is the msg',
           LinkUrl = 'https://eu5.salesforce.com/'+ eventId);
            
           feedList.add(accountFeedItem);
       }
    }
    
    if(!feedList.isEmpty() && feedList.size() >0){
       try 
       {
        insert feedList; 
       } 
       catch (DMLException ex)
       {
        /*****************************************************
        * This section needs to be filled after the Error Log*
        * object is created.
        ******************************************************/ 
       }
    }
  }
}

This is the one that only have 47% I managed to get up to 62% on the EventAfterUpdateClass. I use Kevin Ohara trigger architectural design model for my triggers, that is why I'm casting this "for(Event e : (List<Event>) trigger.new)".
Everything works just fine ... it is the testing that is getting a bit hard :( ....

Thanks for the pointing out the @isTest on the centralize object initialization code ... :) ..