2

RecordTypeId is automatically selected when we query records with SOQL.

This executes just fine in the anonymous console:

Case c = new Case(RecordTypeId = '0120O000000jopF');
insert c;
Id rt = [SELECT Id FROM Case WHERE Id = :c.Id].RecordTypeId;
System.debug(rt);

But somehow it is not reliably working in Tests:

@isTest
public class CaseTest {

    @isTest
    public static void typeIdIsQueried() {
        Exception unexpected = null;

        Case c = new Case(RecordTypeId = '0120O000000jopF');
        insert c;

        try {
            Id rt = [SELECT Id FROM Case WHERE Id = :c.Id].RecordTypeId;
        }
        catch(Exception e) {
            unexpected = e;
        }

        System.assertEquals(null, unexpected);
    }
}

Results in:

System.AssertException: Assertion Failed: Expected: null, Actual: System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: Case.RecordTypeId

It shouldn't work this way, right? guess it's a platform bug!?

EDIT: same with @isTest(SeeAllData=true)

  • What API version is the anonymous console? What API version is the CaseTest class operating under? – ImJohnMDaniel Oct 10 '17 at 15:04
  • both are 40, tried it with test at 36, that's the lowest api version I could set it in the console, same result.. – Basti Oct 10 '17 at 15:12
  • 3
    Seems a difference in test methods vs live. Best bet is to always explicitly include fields you need in your query and not rely on platform (sans Id field of course) – Eric Oct 10 '17 at 16:33
-1

It’s actually interesting that it is working in the anonymous console. You try to access a field in dot notation that you didn’t retrieve.

Shouldn’t the query be:

Id rt = [SELECT Id, RecordTypeId FROM Case WHERE Id = :c.Id].RecordTypeId;

The console might fetch the whole object in interactive mode - so it’s rather a bug in the console.

Does that work for you?

  • I presume you used the magic number for illustration only and not in actual code – stwissel Oct 10 '17 at 16:17
  • Id and RecordTypeId are always queried regardless of your SELECT clause. At least in the Developer Console. Id is included in all Apex. – Adrian Larson Oct 10 '17 at 16:20
  • @AdrianLarson In theory - yes. Guaranteed - seems not – stwissel Oct 10 '17 at 16:23
  • @stwissel it's not a bug in the console, this also applies for regular apex classes, as stated in the posted link. In this question I'm just pointing out that it's not true for tests. – Basti Oct 10 '17 at 16:31
  • Does it work when you explicitly name the field? – stwissel Oct 10 '17 at 16:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.