[SalesForce] Unit Tests: create completed tasks for ActivityHistory

In unit tests, is there a specific way of creating completed tasks so that they appear immediately in the ActivityHistory read-only object? (I have batch Apex that pulls data from ActivityHistory, so I'm trying to write the unit test.)

See code snippet below. When I run the unit test, the activity history is empty. However, when I create completed tasks manually in the UI, the ActivityHistory is populated, and then when I run the batch Apex manually, it works as expected. I just can't get the unit test to put the data into ActivityHistory.

Account acct = new Account(Name = 'Apex Test');
insert acct;

Task tsk1 = new Task(WhatId = acct.Id, Subject = 'Email: apex test', ActivityDate = date.today(), Status = 'Completed');
Task tsk2 = new Task(WhatId = acct.Id, Subject = 'Call: apex test', ActivityDate = date.today(), Status = 'Completed');
Task tsk3 = new Task(WhatId = acct.Id, Subject = 'Email: apex test', ActivityDate = date.today().addYears(-2), Status = 'Completed');
Task[] tskList = new List<Task>{ tsk1, tsk2, tsk3 };
insert tskList;

Account result = [select Id, (SELECT ActivityDate, Subject FROM ActivityHistories) from Account where Id = :acct.Id];

Best Answer

David, have you tried setting the SeeAllData modifier to true for your test class?

I tried out your code, and it appears that in order for you to validate that the ActivityHistory table was populated, you need start your test class with this: @isTest(SeeAllData = true)

Related Topic