phpspec强制方法-返回值

phpspec force method-returned value

我正在尝试测试一个从另一个方法获取数据的 class 方法。
所以我这样做了:

function it_should_return_json_file_as_array()
{
    $this->exist()->willReturn(true);
    $this->read()->willReturn("{\"key\":\"value\"}");
    $this->getContent()->shouldHaveKeyWithValue('key', 'value');
}

但是当我启动 phpspec run 时,我得到了这个:

[InvalidArgumentException]
String "" is not a valid classname. 
Please see reference document: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md  

这是怎么回事?

不可能对您指定的 class 的方法进行存根,而且这是故意不可能的。

PhpSpec 试图告诉您您决定的设计方式存在问题。

参见My top ten favourite PhpSpec limitations - Limitation #2

This limitation can become very visible in the case of using inheritance to extend behaviour. We inherit a class and want to add a new method that internally delegates some behaviour to a parent class method. We cannot mock or stub that method. This has lead me again and again to favour composition over inheritance, which is a golden principle in OO design. In the few cases in which inheritance is justified, we can isolate the reusable behaviour into a separate object and use composition in the parent object, allowing us to replace the collaborator with a double.

另请阅读Partial Mocking