7

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

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)

  • 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. – David Cheng Jan 30 '14 at 17:18
  • 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 Mar 24 '14 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 – Xtremefaith May 5 '15 at 19:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.