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.

Revisions

  1. techieshark created this gist Feb 6, 2025.
    28 changes: 28 additions & 0 deletions instanceof_test_apex.cls
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    // 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);
    }