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
ManoharSFManoharSF 

System.Today() and System.Now() in test class

How can we mockup System.Today() and System.Now() in Test class for any further logic?

 

 

Thank you,

Manohar

bob_buzzardbob_buzzard

Can you clarify what you mean by mock up?  Do you want them to return a specific date or date/time?

ManoharSFManoharSF

Hi Bob,

 

I have Batchable class that have this following logic

 

A Case is created by user sometime back say 4hrs back.

 

Then for the Case, my class checks if there's any activity in Task object between the time the case has been created and Now(). if there's none then it will create records in couple custom object.

 

I have another post that has the class and test class that I came up trying to mock the Now() and earlier date but doesnt help.

 

http://boards.developerforce.com/t5/Apex-Code-Development/Test-coverage-for-batchable-class/m-p/687621#M128010

 

Hope that clarifies my intent.

 

Thank you,

Manohar

 

 

 

 

bob_buzzardbob_buzzard

I would use dependency injection for this.  

 

Allow your test class to store a value into a private property of the class, then check to see if you are running a test, and if you are use that instead.  Something along the lines of:

 

@TestVisible
private DateTime testNow {get; set;}

....

// in the method
DateTime nowDT;
if ( (Test.isRunningTest() && (null!=testNow) )
{
   nowDT=testNow;
}
else
{
   nowDT=System.now();
}

// do whatever you need to do with nowDT

 Then in the test class:

MyClass theClass=new MyClass();
myClass.testNow=System.now().addHours(4);

 replacing MyClass with the instance of the class that you are testing.

 

This way, the test can specify what now should be taken as if it needs to, otherwise the code will default to the System.now() value.