Salesforce

Code Snippet: DLRS Tests for Service Appointments

Declarative Lookup Rollup Summaries (DLRS) is a powerful tool, but it doesn’t always play nicely with Salesforce Field Service. In particular, DLRS test execution often fails when referencing ServiceAppointment records. This is because Field Service imposes strict prerequisites; certain objects and values must exist before a ServiceAppointment can even be inserted.

In one client’s org, our Apex tests already handled these setup requirements. But when configuring DLRS rollups, we still received vague errors during the test execution phase. Online documentation offered little clarity on how to make the DLRS “Test Code” field compatible with Field Service.  Only this error was displayed in DLRS:

 

dlrs_ServiceAppointmentTrigger:Test coverage of selected Apex Trigger is 0%, at least 75% test coverage is required

Our Solution

Here’s what worked for us. Adding the following snippet directly into the Test Code field of the DLRS rollup record allowed the rollup logic to execute successfully in a Field Service-enabled org:

Test.setMock(HttpCalloutMock.class, new AthenaCalloutMock());
Account testAccount = TestDataFactory.createAccount('FamilyName');
Contact testContact = TestDataFactory.createContact(testAccount.Id, 'LastName', 'memberId1234');

TestDataFactory.setupFieldService();        
WorkType wt = [SELECT Id FROM WorkType LIMIT 1];
DateTime futureStart = DateTime.newInstance(DateTime.now().addYears(1).year(), 1, 1, 1, 0, 0);
ServiceAppointment primaryAppt = TestDataFactory.createServiceAppointment(
    testAccount.Id,
    testContact.Id,
    wt.Id,
    'Scheduled',
    futureStart
); 

Savepoint sp = Database.setSavepoint();
dlrs.RollupService.testHandler(primaryAppt);
Database.rollback(sp);

This code makes use of our Apex TestDataFactory class to create a valid Field Service setup and configuration, as well as records that properly relate to each other. You may need to adapt the code to work properly in your org.  See below for additional technical reading.

When in Doubt, Ask

If your team is hitting roadblocks with DLRS, Field Service, or other tricky Salesforce edge cases, reach out. Cloud Notions can help you get things rolling.

Want to Learn More?

We'd be happy to dive into details or answer technical questions.  Feel free to contact us today!