Can I “Mock” time in PHPUnit?

后端 未结 11 510
梦谈多话
梦谈多话 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:11

    Carbon::setTestNow(Carbon $time = null) makes any call to Carbon::now() or new Carbon('now') return the same time.

    https://medium.com/@stefanledin/mock-date-and-time-with-carbon-8a9f72cb843d

    Example:

        public function testSomething()
        {
            $now = Carbon::now();
            // Mock Carbon::now() / new Carbon('now') to always return the same time
            Carbon::setTestNow($now);
    
            // Do the time sensitive test:
            $this->retroEncabulator('prefabulate')
                ->assertJsonFragment(['whenDidThisHappen' => $now->timestamp])
    
            // Release the Carbon::now() mock
            Carbon::setTestNow();
        }
    

    The $this->retroEncabulator() function needs to use Carbon::now() or new Carbon('now') internally of course.

提交回复
热议问题