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.
@isTest
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
Test.startTest();
INSERT h;
Test.stopTest();
Highest__c hAfter = [
SELECT Name,
Middle__r.Name,
hAfter.Middle__r.Lower__r.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!
Top comments (1)
Nice discovery Katie. I did make a use of external IDs mostly in the production code context, and that usually reduce number of SOQL statements and produced cleaner code.
Thank you for sharing