在 Phpunit 中使用流畅的界面模拟 class

Mock class with fluent interface in Phpunit

我正在使用没有 return 类型声明的流畅方法来模拟此示例 class:

<?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;
    }   
}

使用 PhpUnit:

$mock = $this->getMockBuilder(Foo::class)
    ->getMock();

默认情况下,如果没有 return 类型声明,这将不适用于流畅的方法,因此我需要添加 ff。:

$mock->method('setX')->will($this->returnSelf());
$mock->method('setY')->will($this->returnSelf());

这可行,但如果有很多流畅的方法,写起来很麻烦。我的问题是,有没有办法为整个 class 而不是每个方法设置这个?

据我所知没有办法做到这一点。这将为某些方法的模拟 return 本身提供一种方法,而 phpunit 模拟没有这样的功能。

如果你需要这个用于很多方法,你可以创建一个手动模拟(只是一个简单的 class 扩展 class-to-mock 并实现魔术方法 __call() (https://www.php.net/manual/en/language.oop5.overloading.php#object.call).