Salesforce, Python, SQL, & other ways to put your data where you need it

Need event music? 🎸

Live and recorded jazz, pop, and meditative music for your virtual conference / Zoom wedding / yoga class / private party with quality sound and a smooth technical experience

Salesforce Apex lets you use external IDs

04 Jan 2022 🔖 salesforce
💬 EN

How did I miss this? Salesforce Apex lets you DML lookup and master-detail relationships by external ID.

This is huge for actually letting me leverage the performance benefits of @testSetup and not worry about the fact that it doesn’t let you see IDs of records you used it to DML without a SOQL query.

public class WowThisWorks {
    @testSetup static void insertSampleData() {
        Lowest__c l = new Lowest__c(External_ID__c='L01', Name='L 0 1');
        INSERT l;
        Middle__c m  = new Middle__c(External_ID__c='M01', Name='M 0 1', Lowest__c=l.Id);
        INSERT m;
    static testMethod void runTest01() {
        Middle__c mFake = new Middle__c(External_ID__c='M01'); // THIS IS THE MAGIC
        Highest__c h = new Highest__c(Name='H 0 1', Middle__r=mFake); // NOTE THE __r INSTEAD OF __C

        INSERT h;
        Highest__c hAfter = [
            SELECT Name, 
            FROM Highest__c 
            LIMIT 1
        String concat = hAfter.Name + ' ~~ ' + hAfter.Middle__r.Name + ' ~~ ' + hAfter.Middle__r.Lower__r.Name;
        System.assertEquals('H 0 1 ~~ M 0 1 ~~ L 0 1', concat);

I’ve got many, many validation tables that Contact can point to, all of which feed into a trigger I need to write tests for. They all have unique required external IDs built into their schemas.

It’s going to be amazing to be able to create test-data Contact records that look up these “validation table” records by their external IDs without using up any SOQL queries or caching the “validation table” records in memory in test classes.

Happy new year to me!

--- ---