8

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

1 Answer 1

9

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)

3
  • Marty, that was it. I had read somewhere that ActivityHistory requires View All Data permission at the UI level - I wonder if that is related, even though the unit test should be running as a system user. Thank you for testing my code. Commented Jan 30, 2014 at 17:18
  • 1
    That is really stupid you have to do SeeAllData in order to get the ActivityHistory to show from a UnitTest. Upvoted your answer since it did the job for me.
    – dphil
    Commented Mar 24, 2014 at 16:18
  • 2
    If you have the SeeAllData modifer set to true doesn't that negate any actual coverage? Hardly seems like the correct solution. In addition with the new Spring 15' release you cannot have any SeeAllData modifiers when you have a @testSetup method Commented May 5, 2015 at 19:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .