Last active
January 19, 2016 15:08
-
-
Save jmoz/5928773 to your computer and use it in GitHub Desktop.
Phpunit mocking and chaining.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Foo\Unit; | |
class Foo | |
{ | |
public function foo($foo = true) | |
{ | |
return $foo; | |
} | |
} | |
class ChainTest extends \PHPUnit_Framework_TestCase | |
{ | |
public function testFooUndefinedMethodError() | |
{ | |
$foo = new Foo(); | |
$this->assertEquals('foo', $foo->foo('foo')); | |
$mock = $this->getMockBuilder('Foo\Unit\Foo') | |
->disableOriginalConstructor() | |
->getMock(); | |
$mock->expects($this->any()) | |
->method('bar') | |
->will($this->returnValue('bar')); | |
$this->assertNull($mock->foo('foo')); // returns null by default for mocked methods when setMethods not called | |
// $mock->bar(); // will throw a php fatal error | |
$this->assertFalse(method_exists($mock, 'bar')); | |
} | |
public function testFooUndefinedMethodWorks() | |
{ | |
$mock = $this->getMockBuilder('Foo\Unit\Foo') | |
->disableOriginalConstructor() | |
->setMethods(array('foo', 'bar')) // mock out both methods but also an undefined method | |
->getMock(); | |
$mock->expects($this->any()) | |
->method('bar') | |
->will($this->returnValue('bar')); | |
$this->assertNull($mock->foo('foo')); | |
$this->assertEquals('bar', $mock->bar()); | |
} | |
public function testFooChained() | |
{ | |
$mock = $this->getMockBuilder('Foo\Unit\Foo') | |
->disableOriginalConstructor() | |
->setMethods(array('bar')) // mock out just bar so foo implementation stays the same | |
->getMock(); | |
$mock->expects($this->any()) | |
->method('bar') | |
->will($this->returnSelf()); // return the stub object so we can chain | |
$this->assertEquals('baz', $mock->bar()->foo('baz')); | |
} | |
public function testFooChainedAt() | |
{ | |
$mock = $this->getMockBuilder('Foo\Foo') | |
->disableOriginalConstructor() | |
->setMethods(array('foo', 'bar', 'baz')) | |
->getMock(); | |
$mock->expects($this->at(4)) // on index 3 of calls, not 1 as expected, against what documentation says | |
->method('foo') | |
->will($this->returnValue('bat')); | |
$mock->expects($this->any()) | |
->method($this->anything()) // all other calls return self | |
->will($this->returnSelf()); | |
$this->assertEquals('bat', $mock->foo()->bar()->foo()->baz()->foo('foo')); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment