Unit testing a function containing DateTime("now")

codeigniter, datetime, php, phpunit, unit-testing

Solution

You could instead pass in the `$date_start` variable to the function, and when you call it in your test it would be the same every time ie

function testMymethod(){
   $date_start = new DateTime('2011-01-01');
   $class->getSomeInfo($id, $date_start);
   //assertions
}

And your method signiture would change to:

    class myclass {
      public function getSomeInfo($id, $date_start = new DateTime()){...}
    }

Problem

I have a function similar to this: ``` public function getSomeInfo($id){ $date_start=new DateTime(); $day_of_week=$date_start->format("N"); $date_start=$date_start->sub(new DateInterval("P".$day_of_week."D")); $date_end=new $date_start; $date_end=$date_end->add(new DateInterval("P5D")); $date_start=$date_start->format("Y-m-d"); $date_end=$date_end->format("Y-m-d"); $sql="SELECT * FROM `table` WHERE `table`.`id`=$id AND `session`.`date`>'$date_start' AND `session`.`date`<='$date_end'"; $this->db->query($sql); } ``` It returns a dataset for this current week, basically selects records from a table with a date between last Monday and This Sunday. I want to be able to unit test this but I don't know how to do this when it is initiating a DateTime constructor. which will be for the current week but actually for testing purposes I only want one week of data in the testing dataset so really I want the test DateTime to be the same date every time. Basically how can I set DateTime("now") to the same mock date everytime. I am using PHP, Codeigniter and PHPUnit/CIUnit (Implied in tags).

Original source