简体   繁体   中英

Mock class with fluent interface in Phpunit

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?

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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM