为什么 phpspec 看不到来自静态构造函数的对象的 shouldBeLike?

Why phpspec does not see shouldBeLike for object from static constructor?

我试图在 phpspec 中使用静态构造函数指定值对象,但问题是 shouldBeLike 是未定义的方法。 times方法返回的对象是new Money,所以我不知道哪里错了...

MoneySpec:

<?php

namespace spec;

use Money;
use PhpSpec\ObjectBehavior;

class MoneySpec extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType(Money::class);
    }

    function it_multiplies()
    {
        $five = Money::dollar(5);
        $five->times(2)->shouldBeLike(Money::dollar(5));
        $five->times(3)->shouldBeLike(Money::dollar(6));
    }
}

金钱:

<?php

class Money
{
    private $amount;

    private function __construct($amount)
    {
        $this->amount = $amount;
    }

    public static function dollar($amount)
    {
        return new Money($amount);
    }

    public function times($multiplier)
    {
        return new Money($this->amount * $multiplier);
    }

    public function getAmount()
    {
        return $this->amount;
    }
}

因为你没有定义它...我在代码中看不到它

对于命名静态构造函数,您需要使用 beConstructedThrough(或所描述的较短语法之一)。例如,对于您的情况:

function it_multiplies()
{
    $this->beConstructedThrough('dollar', [5]);
    $this->times(2)->shouldBeLike(Money::dollar(5));
    $this->times(3)->shouldBeLike(Money::dollar(6));
}