Skip to main content
1 of 2
Brad Ullery
  • 1.5k
  • 3
  • 15
  • 23

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];

My closed task status value is set to "Completed". Have I missed something obvious (or not obvious)?

Brad Ullery
  • 1.5k
  • 3
  • 15
  • 23