I am mocking this sample class with fluent methods that doesn’t have return type declaration:
<?php class Foo { private string $x; private string $y; public function setX(string $x) { $this->x = $x; return $this; } public function setY(string $y) { $this->y = $y; return $this; } }
Using PhpUnit:
$mock = $this->getMockBuilder(Foo::class) ->getMock();
By default, this will not work on fluent methods without return type declaration so I need to add the ff.:
$mock->method('setX')->will($this->returnSelf()); $mock->method('setY')->will($this->returnSelf());
This works but cumbersome to write if there are a lot fluent methods. My question is, is there a way to set this for the entire class instead of per method?
Advertisement
Answer
As far as I know there is no way to do this. This would afford a way to the mock to return itself for a certain set of methods and phpunit mocks do not have such functionality.
If you need this for a lot of methods you could create a manual mock (just a simple class that extends the class-to-mock and implement the magic method __call()
(https://www.php.net/manual/en/language.oop5.overloading.php#object.call).