Friday, January 28, 2022

[FIXED] Laravel/codeception testing: how to stubbing time()

Issue

Is it possible using Laravel mocking, stubling, (and/or Codeception\Test\Unit and/or Codeception\Stub) to make test for method z (public testZ(){...} ) for following class:

<?php

class X extends Y
{
    public function z(string $c = 'c') : array
    {
        return [$c, time()];
    }
}

So, I need time() to return fake value. Uopz & mimus are excluded options (coz it is possible that sooner or later it can be abandoned).

Is there any Laravel/php trick to make reliable test for codes that returns time() as part of returned value?


Solution

If you convert it to Carbon datetime, there is possibilities.

return [$c, now()->timestamp];

Now you can set your fake date in a test and it will return given date when used in the code

Carbon::setTestNow(Carbon::create(2021, 10, 19, 9, 30);


Answered By - mrhn

No comments:

Post a Comment

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