I have the following piece of code that I am trying to run as part of a unit test (test not shown here). I am creating an Account and then creating a Task associated to that Account via the WhatId
1. String recordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('General').getRecordTypeId();
2. User someUser = [Select username from User where username like 'tristan%'][0];
3. Account testAccount = new Account(
RecordTypeId=recordTypeId,
OwnerId=someUser.Id,
Name = 'Test Consulting',
Line_of_Business__c = 'Sport'
);
4. insert testAccount;
5. Task testTask = new Task(
WhatId= testAccount.Id,
OwnerId=someUser.Id,
Subject='Call',
ActivityDate=System.today(),
Priority='Normal'
);
6. insert testTask;
7. System.debug(LoggingLevel.INFO, 'user debug: xxxxxxxxxxx # Tasks account: ' + testTask.AccountId);
The line above (Line 7) prints out a null, however when I query the task again and print the same field back like so (Line 10):
8. Task someTask = [Select Id, AccountId FROM Task where id = :testTask.Id][0];
9. String accId = someTask.AccountId;
10. System.debug(LoggingLevel.INFO, 'user debug: xxxxxxxxxxx # Tasks account ID NOW: ' + accId);
I get the AccountId displayed.
Why does this happen? Why can't I just access the Task.AccountId before querying the Task again? The other Task fields like 'Status' etc. are accessible.