PHP Mocking Final Class PHP Mocking Final Class php php

PHP Mocking Final Class


Since you mentioned you don't want to use any other framework, you are only leaving yourself one option: uopz

uopz is a black magic extension of the runkit-and-scary-stuff genre, intended to help with QA infrastructure.

uopz_flags is a function that can modify the flags of functions, methods and classes.

<?phpfinal class Test {}/** ZEND_ACC_CLASS is defined as 0, just looks nicer ... **/uopz_flags(Test::class, null, ZEND_ACC_CLASS);$reflector = new ReflectionClass(Test::class);var_dump($reflector->isFinal());?>

Will yield

bool(false)


Late response for someone who is looking for this specific doctrine query mock answer.

You can not mock Doctrine\ORM\Query because its "final" declaration, but if you look into Query class code then you will see that its extending AbstractQuery class and there should not be any problems mocking it.

/** @var \PHPUnit_Framework_MockObject_MockObject|AbstractQuery $queryMock */$queryMock = $this    ->getMockBuilder('Doctrine\ORM\AbstractQuery')    ->disableOriginalConstructor()    ->setMethods(['getResult'])    ->getMockForAbstractClass();


I suggest you to take a look at the mockery testing framework that have a workaround for this situation described in the page: Dealing with Final Classes/Methods:

You can create a proxy mock by passing the instantiated object you wish to mock into \Mockery::mock(), i.e. Mockery will then generate a Proxy to the real object and selectively intercept method calls for the purposes of setting and meeting expectations.

As example this permit to do something like this:

class MockFinalClassTest extends \PHPUnit_Framework_TestCase {    public function testMock()    {        $em = \Mockery::mock("Doctrine\ORM\EntityManager");        $query = new Doctrine\ORM\Query($em);        $proxy = \Mockery::mock($query);        $this->assertNotNull($proxy);        $proxy->setMaxResults(4);        $this->assertEquals(4, $query->getMaxResults());    }

I don't know what you need to do but, i hope this help