+ Start a Discussion
goravsethgoravseth 

How to use system.Now() in test class assertion

We have a simple trigger that updates a checkbox on all child records when parent opp is edited.  I'm trying to switch the behavior to updating a date/time field.

Its quite easy to update the code, but I'm having a hard time figuring out how to pass Now() to the system.assert in the test class.

For the code, I changed

  for (Engagement_Role__c er : engagementRolesToUpdate) {
            er.ER_Updated__c = TRUE;
to:
  for (Engagement_Role__c er : engagementRolesToUpdate) {
            er.ER_Update_DateTime__c = system.Now();

In the test class, what I want is something like: 
System.assertEquals(0, [select count() from Engagement_Role__c where  Opportunity__c in :opps and ER_Update_DateTime = system.Now() ]);

That does not work, gives the following error:
Error: Compile Error: expecting a colon, found 'System.Now' at line 47 column 127    

I tried declaring a variable and using that instead:

DateTime testNow = system.Now();
System.assertEquals(0, [select count() from Engagement_Role__c where  Opportunity__c in :opps and ER_Update_DateTime = testNow ]);

And I get an error:   Compile Error: expecting a colon, found 'testNow' at line 49 column 127    

I am not a developer in any meaningful way, just hacking on our code, being dangerous, and very tired to boot.  
Greatly appreciate any pointers as to what i'm missing here.

Thanks as always.
Best Answer chosen by goravseth
Balaji Chowdary GarapatiBalaji Chowdary Garapati

In Query, while comparing with a varaible or return value from a method use ":"(colon) after the = 

for eg.,

 

System.assertEquals(0, [select count() from Engagement_Role__c where  Opportunity__c in :opps and ER_Update_DateTime = : system.Now() ]);

will solve your issue!

Thanks,
balaji

All Answers

Balaji Chowdary GarapatiBalaji Chowdary Garapati

In Query, while comparing with a varaible or return value from a method use ":"(colon) after the = 

for eg.,

 

System.assertEquals(0, [select count() from Engagement_Role__c where  Opportunity__c in :opps and ER_Update_DateTime = : system.Now() ]);

will solve your issue!

Thanks,
balaji

This was selected as the best answer
goravsethgoravseth
Thanks so much Balaji.