Find your content:

Search form

You are here

How do I write test for a Histories Inner query?


I have a query on accounts with an inner query on ActivityHistory

string query;
query =' SELECT id,ownerid,o,';
query+='  (SELECT id,AccountId, WhatId,status,createdDate,activityDate FROM ActivityHistories)';
query += ' FROM account;

Then I have a for loop for the activity history:

for(ActivityHistory acctHist : historiesList){ //some stuff happens here}

When I write my tests creating An account/ contact and task which are all associated I can't get the test to enter that loop?

Here is the test:

    account a1 = new account(); = 'Acct Test 1' +;


    system.debug('***a1***' + a1);

    contact c1 = new contact();
    c1.AccountId = a1.Id;
    c1.FirstName = 'C1 First Name';
    c1.LastName = 'C1 Last Name';

    system.debug('***C1***' + c1);

    task t1 = new task();
    t1.whatId =;
    t1.whoId =;
    t1.Type = 'Call - Outbound';
    t1.status = 'Completed';
    t1.activityDate =;
    t1.calltype = 'Outbound';
    insert t1; 
Test.StartTest(); CallClass = new CallClass(); Test.StopTest();

All of the system debugs show the relationships exist but the loop is still not entered.

Attribution to: Jonathan Jenkins

Possible Suggestion/Solution #1

That does seem odd, I tried executing that just anonymous and it seemed to return a result okay. However just reading about ActivityHistory, it might be an idea to add a ORDER BY and LIMIT Clause to the query. ( This might be particularly relevant especially if you are executing the Test as a User with no View All Data permission.


SELECT id,AccountId, WhatId,status,createdDate,activityDate FROM ActivityHistories ORDER BY ActivityDate DESC, LastModifiedDate DESC LIMIT 10

As an aside, I got

System.assertEquals(1, ((Account)Database.query('Select Id, (Select Id, Status from ActivityHistories) from Account WHERE Id = \'' + acc.Id + '\'')).ActivityHistories.size());

to work

Attribution to: techtrekker

Possible Suggestion/Solution #2

To get around this I have removed the inner query and added an additional one where the list the query populates mirrors the functionality of ActivityHistories.

Thanks for the help/direction/research.

Attribution to: Jonathan Jenkins

Possible Suggestion/Solution #3

How about instead of querying for ActivityHistories, you query for (Events where StartDateTime < and (Tasks where IsClosed = TRUE). Those can be created in a test class, and it seems like you could get the same information that way.

Attribution to: Jeremy Nottingham
This content is remixed from stackoverflow or stackexchange. Please visit

My Block Status

My Block Content