Skip to content

Instantly share code, notes, and snippets.

@techieshark
Created February 6, 2025 20:34
Show Gist options
  • Save techieshark/509bb2a8c98a698943ac89e9af0f1e80 to your computer and use it in GitHub Desktop.
Save techieshark/509bb2a8c98a698943ac89e9af0f1e80 to your computer and use it in GitHub Desktop.
Testing how Apex instanceof handles different string inputs
// Testing how instanceof handles different string inputs.
// It returns false positives.
// for safer alternatives see: https://salesforce.stackexchange.com/questions/392364/apex-instanceof-id-sometimes-false-positive
@isTest static void test_instanceOf() {
// String str = 'cam - 123';
// String str = '701andIamNotARealId';
// String str = '003BC00000ArsxPYAR'; // says this is an ID, but ID is from other org
String str = '243;0919957138;z71'; // says this is an Id; it obviously isn't
Boolean isId;
Test.startTest();
// Id idValue = (Id)str; // this is an alternative to `instanceof`
isId = str instanceof Id;
if (isId) {
System.debug('string ' + str + ' is a valid Id');
} else {
System.debug('string ' + str + ' is NOT a valid Id');
}
Test.stopTest();
System.assert(isId == false);
// System.debug('idValue');
// System.debug(idValue);
// System.assertEquals(str, idValue);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment