Skip to content

Instantly share code, notes, and snippets.

@Ilyes512
Forked from ramsey/Bar.php
Created October 3, 2018 20:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ilyes512/a28ec9ad2feb863e87ebff590a8ebb3a to your computer and use it in GitHub Desktop.
Save Ilyes512/a28ec9ad2feb863e87ebff590a8ebb3a to your computer and use it in GitHub Desktop.
Mocking fluent interfaces with Mockery, and vary return values based on input to methods in the middle of the chain
<?php
namespace Ramsey\Talks;
class Bar
{
public function getSomething(Foo $foo, $arg1, $arg2)
{
$result = $foo->bar()->baz($arg1)->qux()->quux($arg2);
return "Now, we're {$result}";
}
}
<?php
namespace Ramsey\Talks\Test;
class FluentTest extends \PHPUnit_Framework_TestCase
{
public function tearDown()
{
\Mockery::close();
}
public function testFluentInterfacesWithParameterAtEndOfChain()
{
$mock = \Mockery::mock('Ramsey\\Talks\\Foo');
$mock->shouldReceive('bar->baz->qux->quux')
->with(123)
->andReturn('awesome!');
$mock->shouldReceive('bar->baz->qux->quux')
->with(321)
->andReturn('cool!');
$bar = new \Ramsey\Talks\Bar;
$this->assertEquals("Now, we're awesome!", $bar->getSomething($mock, null, 123));
$this->assertEquals("Now, we're cool!", $bar->getSomething($mock, null, 321));
}
public function testFluentInterfacesWithInterveningParameters()
{
$baz = \Mockery::mock('baz');
$baz->shouldReceive('qux->quux')
->with(321)
->andReturn('rad!');
$mock = \Mockery::mock('Ramsey\\Talks\\Foo');
$mock->shouldReceive('bar->baz')
->with(123)
->andReturn($baz);
$bar = new \Ramsey\Talks\Bar;
$this->assertEquals("Now, we're rad!", $bar->getSomething($mock, 123, 321));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment