Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of SimpleTest "partial mocks" in PHPUnit?

I'm trying to migrate a bunch of tests from SimpleTest to PHPUnit and I was wondering if there is an equivalent for SimpleTest's partial mocks.

I can't seem to find anything in the documentation which suggests that this feature is available, but it occurred to me that I could just use a subclass. Is this a good or bad idea?

class StuffDoer {     protected function doesLongRunningThing() {         sleep(10);         return "stuff";     }     public function doStuff() {         return $this->doesLongRunningThing();     } }  class StuffDoerTest {     protected function doesLongRunningThing() {         return "test stuff";     } }  class StuffDoerTestCase extends PHPUnit_Framework_TestCase {     public function testStuffDoer() {         $sd = new StuffDoerTest();         $result = $sd->doStuff();         $this->assertEquals($result, "test stuff");     } } 
like image 718
Shabbyrobe Avatar asked Jul 22 '09 09:07

Shabbyrobe


1 Answers

From reading the linked page, a SimpleTest partial mock seems to be a mock where only some of the methods are overridden. If this is correct, that functionality is handled by a normal PHPUnit mock.

Inside a PHPUnit_Framework_TestCase, you create a mock with

$mock = $this->getMock('Class_To_Mock'); 

Which creates an mock instance where all methods do nothing and return null. If you want to only override some of the methods, the second parameter to getMock is an array of methods to override.

$mock = $this->getMock('Class_To_Mock', array('insert', 'update')); 

will create an mock instance of Class_To_Mock with the insert and update functions removed, ready for their return values to be specified.

This information is in the phpunit docs.

Note, this answer shows more up to date code examples, for PHPUnit versions starting 5.4

like image 110
Brenton Alker Avatar answered Oct 03 '22 07:10

Brenton Alker