TRi*_*iNE 2 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;
/**
* @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";
}
?>
Run Code Online (Sandbox Code Playgroud)
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.
}
?>
Run Code Online (Sandbox Code Playgroud)
如果时钟嘲弄成功,assertEquals应该通过.但它没有通过,实际时间保持不变.声明两个字符串相等的失败.
--- Expected
+++ Actual
@@ @@
-'2016-11-05 01:00:00'
+'2016-05-29 16:44:49'
FAILURES!
Tests: 9, Assertions: 16, Failures: 1.
Run Code Online (Sandbox Code Playgroud)
任何建议实现欲望功能是值得赞赏的.
我正在学习本教程.
使用ClockMock::withClockMock这样:
ClockMock::withClockMock(strtotime('2016-11-05 01:00:00'));
Run Code Online (Sandbox Code Playgroud)
此外,无需覆盖该time()功能.
| 归档时间: |
|
| 查看次数: |
687 次 |
| 最近记录: |