function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
dmchengdmcheng 

Unit Tests: create completed tasks for ActivityHistory?

Hello.  In unit tests, is there a specific way of creating completed tasks so that they appear immediately in the ActivityHistory read-only object?   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.

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 chosen by dmcheng
dmchengdmcheng
I got the answer from stackexchange - for some reason, we need to use  @isTest(seeAllData=true) in order to see ActivityHistory in unit tests.

All Answers

Sonam_SFDCSonam_SFDC
When you create any records through test classes - they are not committed to the database so ideally it would not be shown on the UI when you check the related list.

Read more:http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_testing_unit_tests.htm
Unit test consideration: Since test methods don’t commit data created in the test, you don’t have to delete test data upon completion.


dmchengdmcheng
Yes I understand that, but they are committed within the context of the unit test, so it seems like they should appear in ActivityHistory during the unit test.
Sonam_SFDCSonam_SFDC
They are not committed to the database during test execution - so they will not be visible on the UI at any point of time if its created through the test class.
dtravellerdtraveller
I am not talking about the UI.  Forget I said anything about the UI.  I am deleting what I said about the UI.

This line in the unit test does not return any activities.  Why is that?
Account result = [select Id (SELECT ActivityDate, Subject FROM ActivityHistories) from Account where Id = :acct.Id];
dmchengdmcheng
I got the answer from stackexchange - for some reason, we need to use  @isTest(seeAllData=true) in order to see ActivityHistory in unit tests.
This was selected as the best answer
MagnetismMagnetism
I also have the same issue with the test class, did you find a solution for this?