Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit: mock non-existing classes

Tags:

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!

like image 904
Kuba T Avatar asked Jan 24 '15 12:01

Kuba T


1 Answers

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(); 
like image 198
Sebastian Bergmann Avatar answered Jan 03 '23 11:01

Sebastian Bergmann