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
DML2020DML2020 

Examples of platform event trigger test classes

I've validated a changeset which returned code coverage failure (even though unrelated to the code being deployed) for an event trigger after running default tests. In order to get the desired code deployed, a test class covering the event trigger needs to be created.

I'm not sure how to go about this and would like to see examples of what a test class for an event trigger would look like.

Here's the event trigger I need coverage for:

trigger MYLogEventTrigger on MYLogEvent__e (after insert) {
List<MYLogEvent__e> eventlist = (List<MYLogEvent__e>) trigger.new;
MY_Util.handleNewEvents(eventlist);
}

Suraj Tripathi 47Suraj Tripathi 47

Hi,

You can take references from the below code.

Trigger AccountEventTrigger on Event (Before Insert) {
    
/******************************************************************************
It controlls the creation of Events from accounts which are yet to be approved.
*******************************************************************************/
    list<Id> accountIds = new list<Id>();
    Map<Id,Account> accMap = new Map<Id,Account>();
    for(Event Event: Trigger.new){
        if(Event.whatId != null && String.valueof(Event.whatId).startsWith('001'))
            accountIds.add(Event.whatId);
    }
    if(!accountIds.isEmpty()){
        for(Account acc : [select id,Submitted_for_Approval__c from Account where id in : accountIds]){
            accMap.put(acc.id,acc);
        }   
        for(Event Event: Trigger.New){
            if(Event.whatId != null && accMap.containsKey(Event.whatId) && accMap.get(Event.whatId).Submitted_for_Approval__c!= false)
                Event.addError('New Event Cannot be Created');
        }
    } 
}

test class:

@isTest
public class AccountEventTriggerTest {

    static testMethod void myUnitTest1(){
        
        Account a= new Account ();
        a.name='Test Account';
        a.Submitted_for_Approval__c=true;
        insert a;
        
        Event e = new Event();
        e.WhatId=a.id;
        e.StartDateTime=system.today();
        e.EndDateTime=system.today()+5;
        
        Test.startTest();  
			try
			{
				insert  e;       
			}
			catch(Exception ex)
			{
				Boolean expectedExceptionThrown =  ex.getMessage().contains('New Event Cannot be Created') ? true : false;
				System.AssertEquals(expectedExceptionThrown, true);                
			}
		Test.stopTest();  
    }
}


Please mark it as the Best Answer if it helps you.

Thank You