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?
When you want to mock a final class, its a perfect moment to make use of Dependency inversion principle:
For the mocking it means: Create an abstraction (interface or abstract class) and assign it to the final class, and mock the abstraction.
I stumbled upon the same problem with
Doctrine\ORM\Query
. I needed to unit test the following code:createQuery
returnsDoctrine\ORM\Query
object. I couldn't useDoctrine\ORM\AbstractQuery
for my mock because it doesn't havesetMaxResults
method and I didn't want to introduce any other frameworks. To overcome thefinal
restriction on the class I use anonymous classes in PHP 7, which are super easy to create. In my test case class I have:Then in my test:
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.
Funny way :)
PHP7.1, PHPUnit5.7
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:
As example this permit to do something like this:
I don't know what you need to do but, i hope this help
I've implemented @Vadym approach and updated it. Now I use it for testing successfully!