我正在使用PHPUnit测试我的Symfony2项目。我想在做一些功能测试时模拟服务器的时钟。
AuthUserRepositoryTest.php
<?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";
}
?>
AuthUserRepository.php
<?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.
}
?>
如果时钟模拟成功,assertEquals
应该通过。但它没有通过,实际时间保持不变。
无法断言两个字符串相等。
--- Expected
+++ Actual
@@ @@
-'2016-11-05 01:00:00'
+'2016-05-29 16:44:49'
FAILURES!
Tests: 9, Assertions: 16, Failures: 1.
赞赏任何实现愿望功能的建议。
我正在关注this教程。
答案 0 :(得分:5)
像这样使用ClockMock::withClockMock
:
ClockMock::withClockMock(strtotime('2016-11-05 01:00:00'));
此外,无需覆盖time()
函数。