[SalesForce] Create Task Activity in Unit Test

I am apparently missing something in the creation of my unit test data. I would like to create both an Account and an Open Activity (task) for the account.

I am able to successfully insert both records, and I receive results when querying the Account and Task individually. My issue is when I attempt to find the Open Activities for the Account.

Account Creation Code

Account a = new Account(Name='Sample Account');
insert a;

Task Creation Code

List<Task> tasks = new List<Task>();
tasks.add(new Task(
    ActivityDate = Date.today().addDays(7),
    Subject='Sample Task',
    WhatId = a.Id,
    OwnerId = UserInfo.getUserId(),
    Status='In Progress'));

insert tasks;

After the records are created, this query returns results:

Id aId = a.Id;
List<Task> taskRecords = [Select Id, WhatId, Subject from Task where WhatId = :aId];

While this does not:

List<Account> accountWithOpenActivities = [Select Name, (Select Id, WhatId, Subject From OpenActivities) from Account where Id = :aId];

Best Answer

Any chance your running user in the testmethod falls afoul of these restrictions (from SFDC Doc)

In order to prevent performance issues while still providing the related list functionality, there are some restrictions on users who do not have “View All Data” permission. Such users must comply with the following restrictions:

In the main clause of the relationship query, you can reference only one record. For example, you cannot filter on all records where the account name starts with A, but must reference a single account record.

You cannot use WHERE clauses.

You must specify a limit to the number of rows returned, less than 500.

You must sort on ActivityDate and LastModifiedDate, descending order: ORDER BY ActivityDate DESC, LastModifiedDate DESC

Related Topic