Unit testing a function containing DateTime ("now")

I have a function like 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 the 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, but I don’t know how to do this when it runs the DateTime constructor. which will be for the current week, but actually for testing purposes. I only need one week of data in the test dataset, so I really want the DateTime test to be the same date every time.

Basically, how can I set DateTime ("now") to the same layout date every time. I use PHP, Codeigniter and PHPUnit / CIUnit (implied in tags).

+3
2

$date_start , , , ..

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

:

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

( ) :

  • . TimeProvider , , ServiceContainer , TimeProvider, , .

  • ( ) .

.

+3

All Articles