Symfony2 PHPUnit时钟模拟不工作
我正在使用PHPUnit测试我的Symfony2项目。我想在做一些功能测试时模拟服务器的时钟 AuthUserRepositoryTest.phpSymfony2 PHPUnit时钟模拟不工作,php,unit-testing,symfony,Php,Unit Testing,Symfony,我正在使用PHPUnit测试我的Symfony2项目。我想在做一些功能测试时模拟服务器的时钟 AuthUserRepositoryTest.php <?php namespace AppBundle\Tests\Entity; use AppBundle\Entity\AuthUserRepository; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; use \Symfony\Bridge\PhpUnit\ClockMock;
<?php
namespace AppBundle\Tests\Entity;
use AppBundle\Entity\AuthUserRepository;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use \Symfony\Bridge\PhpUnit\ClockMock;
/**
* @group time-sensitive
*/
class AuthUserRepositoryTest extends WebTestCase
{
/**
* @var AuthUserRepository
*/
private $AuthUserRepository;
public function setUp()
{
$kernel = static::createKernel();
$kernel->boot();
$this->AuthUserRepository = $kernel->getContainer()
->get('doctrine.orm.entity_manager')
->getRepository('AppBundle:auth_user');
ClockMock::register(__CLASS__);
}
/**
* @group time-sensitive
*/
public function test()
{
ClockMock::withClockMock(true);
// Other tests ...
// Check whether clock mock was successful
$time = $this->AuthUserRepository->getApparentTime();
$this->assertEquals("2016-11-05 01:00:00",$time);
}
/**
* Override time() in current namespace for testing
*
* @return int
*/
public static function time()
{
return "2016-11-05 01:00:00";
}
?>
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\EntityRepository;
class AuthUserRepository extends EntityRepository{
private function getTimeStamp()
{
return \DateTime::createFromFormat('U', time())->setTimezone(new \DateTimeZone('Asia/Colombo'))->format('Y-m-d H:i:s');
}
public function getApparentTime()
{
return $this->getTimeStamp();
}
// Functions to be tested are reduced.
}
?>
如有任何关于实现所需功能的建议,我们将不胜感激
下面是教程。使用
ClockMock::withClockMock
如下:
ClockMock::withClockMock(strtotime('2016-11-05 01:00:00'));
此外,无需重写
time()
函数。谢谢你。很好用!
ClockMock::withClockMock(strtotime('2016-11-05 01:00:00'));