Can I “Mock” time in PHPUnit?

后端 未结 11 514
梦谈多话
梦谈多话 2020-11-29 01:53

... not knowing if \'mock\' is the right word.

Anyway, I have an inherited code-base that I\'m trying to write some tests for that are time-based. Trying not to be <

11条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-29 02:26

    I had to simulate a particular request in future and past date in the app itself (not in Unit Tests). Hence all calls to \DateTime::now() should return the date that was previously set throughout the app.

    I decided to go with this library https://github.com/rezzza/TimeTraveler, since I can mock the dates without altering all the codes.

    \Rezzza\TimeTraveler::enable();
    \Rezzza\TimeTraveler::moveTo('2011-06-10 11:00:00');
    
    var_dump(new \DateTime());           // 2011-06-10 11:00:00
    var_dump(new \DateTime('+2 hours')); // 2011-06-10 13:00:00
    

提交回复
热议问题