Search code examples
phplaraveltestinglaravel-testing

How to mock time() function while testing in Laravel?


I'm doing a maths contest project using Laravel. All of the controller methods in the project uses a lot of time() functions.

Questions are returned to the user depending on whether the current time is in between the contest live time.

While writing the feature test and unit tests, how do I mimic the time() functions in the controller so as to set my desired time while running tests for the project?


Solution

  • I think Carbon should be used instead of time():

    Carbon::now()->timestamp // Or just now()->timestamp in 5.5+
    

    You can easily mock Carbon instances.

    If you don't use time() a lot, you could also create your own helper:

    function timestamp()
    {
        if (app()->runningUnitTests()) {
            return ....
        } else {
            return time();
        }
    }
    

    And use it instead of time():

    timestamp()