I'm trying to get a number of records inserted into the database sometime in the past, to allow for a cleanup batch to have proper test coverage. I can use Test.setCreatedDate
on the account I'm attaching a number of notes too, but I can't use it on the notes themselves.
@isTest
public static void Test_SetCreatedDate() {
Note n = new Note();
n.Title = 'Naming Criteria';
n.Body = 'Testing Note.';
Account a = Generate.CreateAccount();
insert a;
n.ParentId = a.Id;
insert n;
Test.setCreatedDate(a.Id, DateTime.now().addMonths(-6));
Test.setCreatedDate(n.Id, DateTime.now().addMonths(-6));
Test.startTest();
a = [SELECT Id, CreatedDate FROM Account WHERE Id = :a.Id];
n = [SELECT Id, CreatedDate FROM Note WHERE Id = :n.Id];
System.assertEquals(DateTime.now().addMonths(-6), a.CreatedDate);
System.assertEquals(DateTime.now().addMonths(-6), n.CreatedDate);
Test.stopTest();
}
This code is failing with:
System.NoDataFoundException: The sObject with the ID 002m0000000m2rjAAA isn’t part of
this transaction. Provide the ID of an sObject that this test method created.
As far as I can tell, this is a test method, with everything (including the Generate
class), located in a test context.
Heres the Generate.CreateAccount
function, requested in the comments. All it does is act as a scaffold to provide data that fulfills the requirements for record creation, without inserting a record.
private final static User user = [SELECT Id FROM User WHERE IsActive = true LIMIT 1];
@testVisible
private static Account CreateAccount() {
Account account = new Account();
account.Name = 'Test';
account.OwnerId = user.Id;
account.Description = 'Used for testing.';
account.NumberOfEmployees = 1;
// other fields
return account;
}
today
that testmethods can set to any value; then you insert sobjects with createdDate=today's date but the code can pretend to run in the past, present, or future