PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, February 21, 2022

[FIXED] CakePHP 3: Set current time for unit testing

 February 21, 2022     cakephp, cakephp-3.0, unit-testing     No comments   

Issue

With CakePHP 3, I'm using the built in class Cake\I18n\Time to calculate the difference in time from an API response and the current time. The results are getting stored for a unit test, but I don't know how to set what the current time is, so the expected results keep changing.

Here's the unit I'm trying to test:

$apiTime = Time::createFromTimestamp($apiTimestamp);

// Get the time the prediction was generated
$currentTime = Time::now();

return (int)(($apiTime->getTimestamp() - $currentTime->getTimestamp()) / 60);

So, is there any way that I can set the current time? That way I would be able to actually know what the expected results are.


Solution

(from http://book.cakephp.org/3.0/en/core-libraries/time.html#creating-time-instances)

In test cases you can mock out now() using setTestNow():

// Fixate time.
$now = new Time('2014-04-12 12:22:30');
Time::setTestNow($now);

// Returns '2014-04-12 12:22:30'
$now = Time::now();

// Returns '2014-04-12 12:22:30'
$now = Time::parse('now');


Answered By - Ethan
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing