Skip to main content

I'm using Data Cloud, I've created a Calculated Insight and am trying to fire that off to the SF instance to update the contact record with a piece of information. So I'm using Data Actions with a Target of a SF Platform Event. The documentation on this is very light, but I've gathered you need Apex to subscribe to the event via a trigger on DataObjectDataChgEvent. I have the code that does this and updates the contact as needed.

 

My issue is I can't write a test class for this trigger, when I try to publish the event in the test class using 

EventBus.publish(new List<DataObjectDataChgEvent> { ev1, ev2 });

I get the following error at this line: System.TypeException: DML operation INSERT not allowed on DataObjectDataChgEvent

 

Makes sense since the docs for this object doesn't have create() as a supported call. However I then wonder how we can ever deploy an apex trigger on this object to prod to subscribe to the Data Action? 

 

#Salesforce Developer

2 个回答
  1. 8月21日 23:37

    Trying this in 2026 it is possible to publish DataObjectDataChgEvent events in a test context. 

     

    Test method.

    @IsTest

    public static void testEventDataCloud() {

    Test.enableChangeDataCapture();

    // Insert one or more test records

    DataObjectDataChgEvent de = new DataObjectDataChgEvent();

    de.ActionDeveloperName = 'Foo';

    //Database.SaveResult sr = EventBus.publish(de);

    Database.SaveResult sr = EventBus.publishWithAccessLevel(de, AccessLevel.SYSTEM_MODE);

    System.assert(sr.isSuccess());

    // Deliver test change events

    Test.getEventBus().deliver();

    List<Account> accs = [Select Id, Name from Account];

    Assert.areEqual(1, accs.size());

    Assert.areEqual(de.ActionDeveloperName, accs[0].Name);

    }

     

    Trigger

    trigger DataObjectDataTrigger on DataObjectDataChgEvent (after insert) {

    System.debug(Trigger.new);

    List<Account> accs = new List<Account>();

    for (DataObjectDataChgEvent event : Trigger.new) {

    // Read properties from the Data Cloud event payload

    String actionName = event.ActionDeveloperName;

    String currentValues = event.PayloadCurrentValue;

    // Fields populated by event publishing

    Assert.isNotNull(event.EventUuid);

    Assert.isNotNull(event.ReplayId);

    Account a = new Account(Name = event.ActionDeveloperName);

    accs.add(a);

    }

    insert accs;

    }

     

    I realise this usage to insert an Account based on the ActionDeveloperName is not how this event type would be used at all in reality, but it does show that the trigger is able to be exercised from an Apex test.

0/9000