Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Mocking Final Class

I am attempting to mock a php final class but since it is declared final I keep receiving this error:

PHPUnit_Framework_Exception: Class "Doctrine\ORM\Query" is declared "final" and cannot be mocked.

Is there anyway to get around this final behavior just for my unit tests without introducing any new frameworks?

like image 454
DanHabib Avatar asked Aug 25 '15 20:08

DanHabib


2 Answers

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.

<?php final 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) 
like image 159
Joe Watkins Avatar answered Sep 25 '22 07:09

Joe Watkins


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(); 
like image 43
wormhit Avatar answered Sep 23 '22 07:09

wormhit