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


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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)

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x