dimanche 29 mai 2016

Symfony2 PHPUnit Clock Mocking not working

I'm testing my Symfony2 project using PHPUnit. I want to mock the server's clock when doing some functional test.

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.
}
?>

If the clock mocking was successful, assertEquals should passed. But it doesn't pass and actual time remains same. Failed asserting that two strings are equal.

--- Expected
+++ Actual
@@ @@
-'2016-11-05 01:00:00'
+'2016-05-29 16:44:49'

FAILURES!
Tests: 9, Assertions: 16, Failures: 1.

Any suggestions to achieve desire functionality is appreciated.

I'm following this tutorial.

Aucun commentaire:

Enregistrer un commentaire