Is it possible to create a mock of non-existing class in PHPUnit?
Let's assume I have some class that creates instance of another class, for example:
class TaskRunner { public function runTasks() { // Run through some loop to get tasks and store each in $taskName // Get task instance by given task name $task = $this->getTaskInstance($taskName); if ($task instanceof AbstractTask) { $task->run(); } } protected function getTaskInstance($taskName) { // Just an example return new $taskName(); } }
I would like to run unit test for runTasks
method to check if created task instace extends some abstract class.
Is there any possibility to NOT to create sample class in a filesystem to check the inheritance constraint?
Thanks for all!
Yes, it is possible to stub/mock classes that do not exist with PHPUnit. Simply do
$this->getMockBuilder('NameOfClass')->setMethods(array('foo'))->getMock();
to create an object of non-existant class NameOfClass
that provides one method, foo()
, that can be configured using the API as usual.
Since PHPUnit 9, you shall replace :
'NameOfClass'
by \stdClass::class
setMethods
by addMethods
$this->getMockBuilder(\stdclass::class)->addMethods(array('foo'))->getMock();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With